Skip to main content

datafusion_datasource/file_scan_config/
mod.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//! [`FileScanConfig`] to configure scanning of possibly partitioned
6//! file sources.
7
8pub(crate) mod sort_pushdown;
9
10/// Shared `FileScanConfig` <-> proto conversion, gated on the `proto` feature.
11/// Attaches inherent `try_to_proto` / `try_from_proto` /
12/// `parse_table_schema_from_proto` helpers to [`FileScanConfig`] used by every
13/// file source's `try_to_proto` hook.
14#[cfg(feature = "proto")]
15mod proto;
16
17use crate::file_groups::FileGroup;
18use crate::{
19    PartitionedFile, display::FileGroupsDisplay, file::FileSource,
20    file_compression_type::FileCompressionType, file_stream::FileStreamBuilder,
21    file_stream::work_source::SharedWorkSource, source::DataSource,
22    statistics::MinMaxStatistics,
23};
24use arrow::datatypes::Fields;
25use arrow::datatypes::{DataType, Schema, SchemaRef};
26use datafusion_common::config::ConfigOptions;
27use datafusion_common::tree_node::TreeNodeRecursion;
28use datafusion_common::{
29    Constraint, Constraints, Result, ScalarValue, SplitPoint, Statistics,
30    internal_datafusion_err, internal_err,
31};
32use datafusion_execution::{
33    SendableRecordBatchStream, TaskContext, object_store::ObjectStoreUrl,
34};
35use datafusion_expr::Operator;
36
37use crate::source::OpenArgs;
38use datafusion_common::stats::{Precision, is_known_empty};
39use datafusion_physical_expr::expressions::{BinaryExpr, Column};
40use datafusion_physical_expr::projection::{ProjectionExprs, ProjectionMapping};
41use datafusion_physical_expr::utils::reassign_expr_columns;
42use datafusion_physical_expr::{
43    EquivalenceProperties, Partitioning, RangePartitioning, split_conjunction,
44};
45use datafusion_physical_expr_adapter::PhysicalExprAdapterFactory;
46use datafusion_physical_expr_common::physical_expr::{PhysicalExpr, is_volatile};
47use datafusion_physical_expr_common::sort_expr::{LexOrdering, PhysicalSortExpr};
48use datafusion_physical_plan::SortOrderPushdownResult;
49use datafusion_physical_plan::coop::cooperative;
50use datafusion_physical_plan::execution_plan::SchedulingType;
51use datafusion_physical_plan::{
52    DisplayAs, DisplayFormatType,
53    display::{ProjectSchemaDisplay, display_orderings},
54    filter_pushdown::FilterPushdownPropagation,
55    metrics::ExecutionPlanMetricsSet,
56};
57use log::{debug, warn};
58use std::any::Any;
59use std::{fmt::Debug, fmt::Formatter, fmt::Result as FmtResult, sync::Arc};
60
61/// [`FileScanConfig`] represents scanning data from a group of files
62///
63/// `FileScanConfig` is used to create a [`DataSourceExec`], the physical plan
64/// for scanning files with a particular file format.
65///
66/// The [`FileSource`] (e.g. `ParquetSource`, `CsvSource`, etc.) is responsible
67/// for creating the actual execution plan to read the files based on a
68/// `FileScanConfig`. Fields in a `FileScanConfig` such as Statistics represent
69/// information about the files **before** any projection or filtering is
70/// applied in the file source.
71///
72/// Use [`FileScanConfigBuilder`] to construct a `FileScanConfig`.
73///
74/// Use [`DataSourceExec::from_data_source`] to create a [`DataSourceExec`] from
75/// a `FileScanConfig`.
76///
77/// # Example
78/// ```
79/// # use std::sync::Arc;
80/// # use arrow::datatypes::{Field, Fields, DataType, Schema, SchemaRef};
81/// # use object_store::ObjectStore;
82/// # use datafusion_common::Result;
83/// # use datafusion_common::tree_node::TreeNodeRecursion;
84/// # use datafusion_datasource::file::FileSource;
85/// # use datafusion_physical_plan::PhysicalExpr;
86/// # use datafusion_datasource::file_groups::FileGroup;
87/// # use datafusion_datasource::PartitionedFile;
88/// # use datafusion_datasource::file_scan_config::{FileScanConfig, FileScanConfigBuilder};
89/// # use datafusion_datasource::file_stream::FileOpener;
90/// # use datafusion_datasource::source::DataSourceExec;
91/// # use datafusion_datasource::table_schema::TableSchema;
92/// # use datafusion_execution::object_store::ObjectStoreUrl;
93/// # use datafusion_physical_expr::projection::ProjectionExprs;
94/// # use datafusion_physical_plan::ExecutionPlan;
95/// # use datafusion_physical_plan::metrics::ExecutionPlanMetricsSet;
96/// # let file_schema = Arc::new(Schema::new(vec![
97/// #  Field::new("c1", DataType::Int32, false),
98/// #  Field::new("c2", DataType::Int32, false),
99/// #  Field::new("c3", DataType::Int32, false),
100/// #  Field::new("c4", DataType::Int32, false),
101/// # ]));
102/// # // Note: crate mock ParquetSource, as ParquetSource is not in the datasource crate
103/// #[derive(Clone)]
104/// # struct ParquetSource {
105/// #    table_schema: TableSchema,
106/// # };
107/// # impl FileSource for ParquetSource {
108/// #  fn create_file_opener(&self, _: Arc<dyn ObjectStore>, _: &FileScanConfig, _: usize) -> Result<Arc<dyn FileOpener>> { unimplemented!() }
109/// #  fn table_schema(&self) -> &TableSchema { &self.table_schema }
110/// #  fn with_batch_size(&self, _: usize) -> Arc<dyn FileSource> { unimplemented!() }
111/// #  fn metrics(&self) -> &ExecutionPlanMetricsSet { unimplemented!() }
112/// #  fn file_type(&self) -> &str { "parquet" }
113/// #  // Note that this implementation drops the projection on the floor, it is not complete!
114/// #  fn try_pushdown_projection(&self, projection: &ProjectionExprs) -> Result<Option<Arc<dyn FileSource>>> { Ok(Some(Arc::new(self.clone()) as Arc<dyn FileSource>)) }
115/// #  fn apply_expressions(&self, _f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>) -> Result<TreeNodeRecursion> { Ok(TreeNodeRecursion::Continue) }
116/// #  }
117/// # impl ParquetSource {
118/// #  fn new(table_schema: impl Into<TableSchema>) -> Self { Self {table_schema: table_schema.into()} }
119/// # }
120/// // create FileScan config for reading parquet files from file://
121/// let object_store_url = ObjectStoreUrl::local_filesystem();
122/// let file_source = Arc::new(ParquetSource::new(file_schema.clone()));
123/// let config = FileScanConfigBuilder::new(object_store_url, file_source)
124///   .with_limit(Some(1000))            // read only the first 1000 records
125///   .with_projection_indices(Some(vec![2, 3])) // project columns 2 and 3
126///   .expect("Failed to push down projection")
127///    // Read /tmp/file1.parquet with known size of 1234 bytes in a single group
128///   .with_file(PartitionedFile::new("file1.parquet", 1234))
129///   // Read /tmp/file2.parquet 56 bytes and /tmp/file3.parquet 78 bytes
130///   // in a  single row group
131///   .with_file_group(FileGroup::new(vec![
132///    PartitionedFile::new("file2.parquet", 56),
133///    PartitionedFile::new("file3.parquet", 78),
134///   ])).build();
135/// // create an execution plan from the config
136/// let plan: Arc<dyn ExecutionPlan> = DataSourceExec::from_data_source(config);
137/// ```
138///
139/// [`DataSourceExec`]: crate::source::DataSourceExec
140/// [`DataSourceExec::from_data_source`]: crate::source::DataSourceExec::from_data_source
141#[derive(Clone)]
142pub struct FileScanConfig {
143    /// Object store URL, used to get an [`ObjectStore`] instance from
144    /// [`RuntimeEnv::object_store`]
145    ///
146    /// This `ObjectStoreUrl` should be the prefix of the absolute url for files
147    /// as `file://` or `s3://my_bucket`. It should not include the path to the
148    /// file itself. The relevant URL prefix must be registered via
149    /// [`RuntimeEnv::register_object_store`]
150    ///
151    /// [`ObjectStore`]: object_store::ObjectStore
152    /// [`RuntimeEnv::register_object_store`]: datafusion_execution::runtime_env::RuntimeEnv::register_object_store
153    /// [`RuntimeEnv::object_store`]: datafusion_execution::runtime_env::RuntimeEnv::object_store
154    pub object_store_url: ObjectStoreUrl,
155    /// List of files to be processed, grouped into partitions
156    ///
157    /// Each file must have a schema of `file_schema` or a subset. If
158    /// a particular file has a subset, the missing columns are
159    /// padded with NULLs.
160    ///
161    /// DataFusion may attempt to read each partition of files
162    /// concurrently, however files *within* a partition will be read
163    /// sequentially, one after the next.
164    ///
165    /// Note that when `datafusion.execution.enable_file_stream_work_stealing`
166    /// is enabled (the default), files may be reassigned to a different
167    /// partition at runtime unless `preserve_order` or
168    /// `partitioned_by_file_group` is set, so a file is not guaranteed to be
169    /// read by the partition it is grouped under here.
170    pub file_groups: Vec<FileGroup>,
171    /// Table constraints
172    pub constraints: Constraints,
173    /// The maximum number of records to read from this plan. If `None`,
174    /// all records after filtering are returned.
175    pub limit: Option<usize>,
176    /// Read files in the order of [`Self::file_groups`].
177    ///
178    /// [`FileScanConfigBuilder::build`] sets this when the scan has an output
179    /// ordering. Readers use [`Self::preserves_file_order`], which also checks
180    /// the current [`Self::output_ordering`], so clearing this flag never
181    /// reorders a scan that advertises an ordering.
182    pub preserve_order: bool,
183    /// All equivalent lexicographical output orderings of this file scan, in terms of
184    /// [`FileSource::table_schema`]. See [`FileScanConfigBuilder::with_output_ordering`] for more
185    /// details.
186    ///
187    /// [`Self::eq_properties`] uses this information along with projection
188    /// and filtering information to compute the effective
189    /// [`EquivalenceProperties`]
190    pub output_ordering: Vec<LexOrdering>,
191    /// File compression type
192    pub file_compression_type: FileCompressionType,
193    /// File source such as `ParquetSource`, `CsvSource`, `JsonSource`, etc.
194    pub file_source: Arc<dyn FileSource>,
195    /// Batch size while creating new batches
196    /// Defaults to [`datafusion_common::config::ExecutionOptions`] batch_size.
197    pub batch_size: Option<usize>,
198    /// Expression adapter used to adapt filters and projections that are pushed down into the scan
199    /// from the logical schema to the physical schema of the file.
200    pub expr_adapter_factory: Option<Arc<dyn PhysicalExprAdapterFactory>>,
201    /// Statistics for the entire table (file schema + partition columns).
202    /// See [`FileScanConfigBuilder::with_statistics`] for more details.
203    ///
204    /// The effective statistics are computed on-demand via
205    /// [`ProjectionExprs::project_statistics`].
206    ///
207    /// Note that this field is pub(crate) because accessing it directly from outside
208    /// would be incorrect if there are filters being applied, thus this should be accessed
209    /// via [`FileScanConfig::statistics`].
210    pub(crate) statistics: Statistics,
211    /// Declared physical output partitioning for this scan.
212    ///
213    /// Expressions are against the full table schema, before scan projection or
214    /// filtering. `ListingTable` validates partition count before building the
215    /// scan, and direct builders with mismatched counts fall back to
216    /// `UnknownPartitioning`.
217    pub output_partitioning: Option<Partitioning>,
218}
219
220/// A builder for [`FileScanConfig`]'s.
221///
222/// Example:
223///
224/// ```rust
225/// # use std::sync::Arc;
226/// # use arrow::datatypes::{DataType, Field, Schema};
227/// # use datafusion_datasource::file_scan_config::{FileScanConfigBuilder, FileScanConfig};
228/// # use datafusion_datasource::file_compression_type::FileCompressionType;
229/// # use datafusion_datasource::file_groups::FileGroup;
230/// # use datafusion_datasource::PartitionedFile;
231/// # use datafusion_datasource::table_schema::TableSchema;
232/// # use datafusion_execution::object_store::ObjectStoreUrl;
233/// # use datafusion_common::Statistics;
234/// # use datafusion_datasource::file::FileSource;
235///
236/// # fn main() {
237/// # fn with_source(file_source: Arc<dyn FileSource>) {
238///     // Create a schema for our Parquet files
239///     let file_schema = Arc::new(Schema::new(vec![
240///         Field::new("id", DataType::Int32, false),
241///         Field::new("value", DataType::Utf8, false),
242///     ]));
243///
244///     // Create partition columns
245///     let partition_cols = vec![
246///         Arc::new(Field::new("date", DataType::Utf8, false)),
247///     ];
248///
249///     // Create table schema with file schema and partition columns
250///     let table_schema = TableSchema::builder(file_schema)
251///         .with_table_partition_cols(partition_cols)
252///         .build();
253///
254///     // Create a builder for scanning Parquet files from a local filesystem
255///     let config = FileScanConfigBuilder::new(
256///         ObjectStoreUrl::local_filesystem(),
257///         file_source,
258///     )
259///     // Set a limit of 1000 rows
260///     .with_limit(Some(1000))
261///     // Project only the first column
262///     .with_projection_indices(Some(vec![0]))
263///     .expect("Failed to push down projection")
264///     // Add a file group with two files
265///     .with_file_group(FileGroup::new(vec![
266///         PartitionedFile::new("data/date=2024-01-01/file1.parquet", 1024),
267///         PartitionedFile::new("data/date=2024-01-01/file2.parquet", 2048),
268///     ]))
269///     // Set compression type
270///     .with_file_compression_type(FileCompressionType::UNCOMPRESSED)
271///     // Build the final config
272///     .build();
273/// # }
274/// # }
275/// ```
276#[derive(Clone)]
277pub struct FileScanConfigBuilder {
278    object_store_url: ObjectStoreUrl,
279    file_source: Arc<dyn FileSource>,
280    limit: Option<usize>,
281    preserve_order: bool,
282    constraints: Option<Constraints>,
283    file_groups: Vec<FileGroup>,
284    statistics: Option<Statistics>,
285    output_ordering: Vec<LexOrdering>,
286    output_partitioning: Option<Partitioning>,
287    file_compression_type: Option<FileCompressionType>,
288    batch_size: Option<usize>,
289    expr_adapter_factory: Option<Arc<dyn PhysicalExprAdapterFactory>>,
290}
291
292impl FileScanConfigBuilder {
293    /// Create a new [`FileScanConfigBuilder`] with default settings for scanning files.
294    ///
295    /// # Parameters:
296    /// * `object_store_url`: See [`FileScanConfig::object_store_url`]
297    /// * `file_source`: See [`FileScanConfig::file_source`]. The file source must have
298    ///   a schema set via its constructor.
299    pub fn new(
300        object_store_url: ObjectStoreUrl,
301        file_source: Arc<dyn FileSource>,
302    ) -> Self {
303        Self {
304            object_store_url,
305            file_source,
306            file_groups: vec![],
307            statistics: None,
308            output_ordering: vec![],
309            output_partitioning: None,
310            file_compression_type: None,
311            limit: None,
312            preserve_order: false,
313            constraints: None,
314            batch_size: None,
315            expr_adapter_factory: None,
316        }
317    }
318
319    /// Set the maximum number of records to read from this plan.
320    ///
321    /// If `None`, all records after filtering are returned.
322    pub fn with_limit(mut self, limit: Option<usize>) -> Self {
323        self.limit = limit;
324        self
325    }
326
327    /// Set whether files must be read in the order of the file groups even
328    /// when the scan has no output ordering. See [`FileScanConfig::preserve_order`].
329    pub fn with_preserve_order(mut self, preserve_order: bool) -> Self {
330        self.preserve_order = preserve_order;
331        self
332    }
333
334    /// Set the file source for scanning files.
335    ///
336    /// This method allows you to change the file source implementation (e.g.
337    /// ParquetSource, CsvSource, etc.) after the builder has been created.
338    pub fn with_source(mut self, file_source: Arc<dyn FileSource>) -> Self {
339        self.file_source = file_source;
340        self
341    }
342
343    /// Return the table schema
344    pub fn table_schema(&self) -> &SchemaRef {
345        self.file_source.table_schema().table_schema()
346    }
347
348    /// Set the columns on which to project the data. Indexes that are higher than the
349    /// number of columns of `file_schema` refer to `table_partition_cols`.
350    ///
351    /// # Deprecated
352    /// Use [`Self::with_projection_indices`] instead. This method will be removed in a future release.
353    #[deprecated(since = "51.0.0", note = "Use with_projection_indices instead")]
354    pub fn with_projection(self, indices: Option<Vec<usize>>) -> Self {
355        match self.clone().with_projection_indices(indices) {
356            Ok(builder) => builder,
357            Err(e) => {
358                warn!(
359                    "Failed to push down projection in FileScanConfigBuilder::with_projection: {e}"
360                );
361                self
362            }
363        }
364    }
365
366    /// Set the columns on which to project the data using column indices.
367    ///
368    /// This method attempts to push down the projection to the underlying file
369    /// source if supported. If the file source does not support projection
370    /// pushdown, an error is returned.
371    ///
372    /// Indexes that are higher than the number of columns of `file_schema`
373    /// refer to `table_partition_cols`.
374    pub fn with_projection_indices(
375        mut self,
376        indices: Option<Vec<usize>>,
377    ) -> Result<Self> {
378        let projection_exprs = indices.map(|indices| {
379            ProjectionExprs::from_indices(
380                &indices,
381                self.file_source.table_schema().table_schema(),
382            )
383        });
384        let Some(projection_exprs) = projection_exprs else {
385            return Ok(self);
386        };
387        let new_source = self
388            .file_source
389            .try_pushdown_projection(&projection_exprs)
390            .map_err(|e| {
391                internal_datafusion_err!(
392                    "Failed to push down projection in FileScanConfigBuilder::build: {e}"
393                )
394            })?;
395        if let Some(new_source) = new_source {
396            self.file_source = new_source;
397        } else {
398            internal_err!(
399                "FileSource {} does not support projection pushdown",
400                self.file_source.file_type()
401            )?;
402        }
403        Ok(self)
404    }
405
406    /// Set the table constraints
407    pub fn with_constraints(mut self, constraints: Constraints) -> Self {
408        self.constraints = Some(constraints);
409        self
410    }
411
412    /// Set the statistics of the files, including partition
413    /// columns. Defaults to [`Statistics::new_unknown`].
414    ///
415    /// These statistics are for the entire table (file schema + partition
416    /// columns) before any projection or filtering is applied. Projections are
417    /// applied when statistics are retrieved, and if a filter is present,
418    /// [`FileScanConfig::statistics`] will mark the statistics as inexact
419    /// (counts are not adjusted).
420    ///
421    /// Projections and filters may be applied by the file source, either by
422    /// [`Self::with_projection_indices`] or a preexisting
423    /// [`FileSource::projection`] or [`FileSource::filter`].
424    pub fn with_statistics(mut self, statistics: Statistics) -> Self {
425        self.statistics = Some(statistics);
426        self
427    }
428
429    /// Set the list of files to be processed, grouped into partitions.
430    ///
431    /// Each file must have a schema of `file_schema` or a subset. If
432    /// a particular file has a subset, the missing columns are
433    /// padded with NULLs.
434    ///
435    /// DataFusion may attempt to read each partition of files
436    /// concurrently, however files *within* a partition will be read
437    /// sequentially, one after the next.
438    pub fn with_file_groups(mut self, file_groups: Vec<FileGroup>) -> Self {
439        self.file_groups = file_groups;
440        self
441    }
442
443    /// Add a new file group
444    ///
445    /// See [`Self::with_file_groups`] for more information
446    pub fn with_file_group(mut self, file_group: FileGroup) -> Self {
447        self.file_groups.push(file_group);
448        self
449    }
450
451    /// Add a file as a single group
452    ///
453    /// See [`Self::with_file_groups`] for more information.
454    pub fn with_file(self, partitioned_file: PartitionedFile) -> Self {
455        self.with_file_group(FileGroup::new(vec![partitioned_file]))
456    }
457
458    /// Set the output ordering of the files
459    ///
460    /// The expressions are in terms of the entire table schema (file schema +
461    /// partition columns), before any projection or filtering from the file
462    /// scan is applied.
463    ///
464    /// This is used for optimization purposes, e.g. to determine if a file scan
465    /// can satisfy an `ORDER BY` without an additional sort.
466    pub fn with_output_ordering(mut self, output_ordering: Vec<LexOrdering>) -> Self {
467        self.output_ordering = output_ordering;
468        self
469    }
470
471    /// Set declared physical output partitioning for this scan.
472    pub fn with_output_partitioning(
473        mut self,
474        output_partitioning: Option<Partitioning>,
475    ) -> Self {
476        self.output_partitioning = output_partitioning;
477        self
478    }
479
480    /// Set the file compression type
481    pub fn with_file_compression_type(
482        mut self,
483        file_compression_type: FileCompressionType,
484    ) -> Self {
485        self.file_compression_type = Some(file_compression_type);
486        self
487    }
488
489    /// Set the batch_size property
490    pub fn with_batch_size(mut self, batch_size: Option<usize>) -> Self {
491        self.batch_size = batch_size;
492        self
493    }
494
495    /// Register an expression adapter used to adapt filters and projections that are pushed down into the scan
496    /// from the logical schema to the physical schema of the file.
497    /// This can include things like:
498    /// - Column ordering changes
499    /// - Handling of missing columns
500    /// - Rewriting expression to use pre-computed values or file format specific optimizations
501    pub fn with_expr_adapter(
502        mut self,
503        expr_adapter: Option<Arc<dyn PhysicalExprAdapterFactory>>,
504    ) -> Self {
505        self.expr_adapter_factory = expr_adapter;
506        self
507    }
508
509    /// Build the final [`FileScanConfig`] with all the configured settings.
510    ///
511    /// This method takes ownership of the builder and returns the constructed `FileScanConfig`.
512    /// Any unset optional fields will use their default values.
513    ///
514    /// # Errors
515    /// Returns an error if projection pushdown fails or if schema operations fail.
516    pub fn build(self) -> FileScanConfig {
517        let Self {
518            object_store_url,
519            file_source,
520            limit,
521            preserve_order,
522            constraints,
523            file_groups,
524            statistics,
525            output_ordering,
526            output_partitioning,
527            file_compression_type,
528            batch_size,
529            expr_adapter_factory: expr_adapter,
530        } = self;
531
532        let constraints = constraints.unwrap_or_default();
533        let mut statistics = statistics.unwrap_or_else(|| {
534            Statistics::new_unknown(file_source.table_schema().table_schema())
535        });
536        add_key_distinct_counts(&constraints, &mut statistics);
537        let file_compression_type =
538            file_compression_type.unwrap_or(FileCompressionType::UNCOMPRESSED);
539
540        // If there is an output ordering, we should preserve it.
541        let preserve_order = preserve_order || !output_ordering.is_empty();
542
543        FileScanConfig {
544            object_store_url,
545            file_source,
546            limit,
547            preserve_order,
548            constraints,
549            file_groups,
550            output_ordering,
551            file_compression_type,
552            batch_size,
553            expr_adapter_factory: expr_adapter,
554            statistics,
555            output_partitioning,
556        }
557    }
558}
559
560/// Records that a key column holds one distinct value per row, which no file format
561/// stores. Single-column keys only: a composite key says nothing about its columns.
562fn add_key_distinct_counts(constraints: &Constraints, statistics: &mut Statistics) {
563    let num_rows = statistics.num_rows;
564    for constraint in constraints.iter() {
565        let (Constraint::PrimaryKey(indices) | Constraint::Unique(indices)) = constraint;
566        let [index] = indices[..] else {
567            continue;
568        };
569        let Some(column) = statistics.column_statistics.get_mut(index) else {
570            continue;
571        };
572        if column.distinct_count != Precision::Absent {
573            continue;
574        }
575        // A NULL is not a distinct value. A primary key has none; a unique column may
576        // repeat them, so an unknown count leaves the result inexact.
577        let nulls = match (constraint, column.null_count) {
578            (Constraint::PrimaryKey(_), Precision::Absent) => Precision::Exact(0),
579            (_, Precision::Absent) => Precision::Inexact(0),
580            (_, nulls) => nulls,
581        };
582        column.distinct_count = num_rows.sub(&nulls);
583    }
584}
585
586impl From<FileScanConfig> for FileScanConfigBuilder {
587    fn from(config: FileScanConfig) -> Self {
588        Self {
589            object_store_url: config.object_store_url,
590            file_source: Arc::<dyn FileSource>::clone(&config.file_source),
591            file_groups: config.file_groups,
592            statistics: Some(config.statistics),
593            output_ordering: config.output_ordering,
594            output_partitioning: config.output_partitioning,
595            file_compression_type: Some(config.file_compression_type),
596            limit: config.limit,
597            preserve_order: config.preserve_order,
598            constraints: Some(config.constraints),
599            batch_size: config.batch_size,
600            expr_adapter_factory: config.expr_adapter_factory,
601        }
602    }
603}
604
605/// Builds `Partitioning::Hash` over `partition_cols` (resolved to their indices in
606/// `schema`). Returns `None` when there are no partition columns.
607#[deprecated(
608    since = "56.0.0",
609    note = "Use `output_range_partitioning_from_split_points` instead"
610)]
611pub fn output_partitioning_from_partition_fields(
612    schema: &Schema,
613    partition_cols: &Fields,
614    partition_count: usize,
615) -> Option<Partitioning> {
616    let exprs = partition_column_exprs(schema, partition_cols)?;
617    Some(Partitioning::Hash(exprs, partition_count))
618}
619
620/// Builds the [`Partitioning::Range`] for file groups from
621/// [`FileGroup::group_by_partition_values_with_split_points`], each column sorted with
622/// `SortOptions::default()` to match how the groups were cut. Returns `None` when there
623/// are no partition columns or one is missing from `schema`, and errors when
624/// `split_points` are not strictly ordered. Split point values must have the partition
625/// column types in `schema`.
626pub fn output_range_partitioning_from_split_points(
627    schema: &Schema,
628    partition_cols: &Fields,
629    split_points: Vec<SplitPoint>,
630) -> Result<Option<Partitioning>> {
631    let Some(exprs) = partition_column_exprs(schema, partition_cols) else {
632        return Ok(None);
633    };
634    let sort_exprs = exprs
635        .into_iter()
636        .map(PhysicalSortExpr::new_default)
637        .collect::<Vec<_>>();
638    let Some(ordering) = LexOrdering::new(sort_exprs) else {
639        return Ok(None);
640    };
641    let range = RangePartitioning::try_new(ordering, split_points)?;
642    Ok(Some(Partitioning::Range(range)))
643}
644
645/// Resolves `partition_cols` to `Column` expressions in `schema`, or `None` when there
646/// are no partition columns or one is missing.
647fn partition_column_exprs(
648    schema: &Schema,
649    partition_cols: &Fields,
650) -> Option<Vec<Arc<dyn PhysicalExpr>>> {
651    if partition_cols.is_empty() {
652        return None;
653    }
654
655    let mut exprs: Vec<Arc<dyn PhysicalExpr>> = Vec::with_capacity(partition_cols.len());
656    for partition_col in partition_cols {
657        let name = partition_col.name();
658        let idx = schema
659            .fields()
660            .iter()
661            .position(|field| field.name() == name)?;
662        exprs.push(Arc::new(Column::new(name, idx)));
663    }
664    Some(exprs)
665}
666
667fn project_output_partitioning(
668    partitioning: &Partitioning,
669    mapping: &ProjectionMapping,
670    input_schema: &SchemaRef,
671    partition_count: usize,
672) -> Partitioning {
673    let input_eq_properties = EquivalenceProperties::new(Arc::clone(input_schema));
674    match partitioning {
675        Partitioning::Hash(exprs, _) => {
676            let projected_exprs = input_eq_properties
677                .project_expressions(exprs, mapping)
678                .collect::<Option<Vec<_>>>();
679            projected_exprs
680                .map(|exprs| Partitioning::Hash(exprs, partition_count))
681                .unwrap_or_else(|| Partitioning::UnknownPartitioning(partition_count))
682        }
683        Partitioning::Range(_)
684        | Partitioning::RoundRobinBatch(_)
685        | Partitioning::UnknownPartitioning(_) => {
686            partitioning.project(mapping, &input_eq_properties)
687        }
688    }
689}
690
691/// Returns `true` if merging `outer` into `inner` would duplicate a volatile or
692/// non-trivial expression that CSE deduplicated; the caller should then decline
693/// the merge.
694///
695/// Merging substitutes each `inner` expression into every `outer` reference to
696/// it. Since the logical optimizer extracts a repeated expression into a single
697/// `inner` entry referenced by column, re-inlining it at more than one
698/// reference site undoes that deduplication. An `inner` expression referenced
699/// more than once is therefore blocked when it is either:
700///
701/// - **volatile** (e.g. `random()`) — evaluating it independently at each site
702///   makes references that should share one "locked-in" value diverge (the
703///   correctness guard the physical `ProjectionPushdown` and `FilterPushdown`
704///   rules also apply via
705///   `datafusion_physical_expr_common::physical_expr::is_volatile`); or
706/// - **not cheap to recompute** — its placement is not push-to-leaves
707///   (`KeepInPlace`: arithmetic, casts, most scalar functions). Leaf-pushable
708///   expressions (columns, `get_field`, `input_file_name`) still merge. This
709///   matches `try_collapse_projection_chain`.
710///
711/// References are counted with multiplicity, so `r + r` counts as two; an
712/// expression referenced exactly once has nothing to duplicate.
713fn would_duplicate_costly_exprs(
714    inner: &ProjectionExprs,
715    outer: &ProjectionExprs,
716) -> bool {
717    use datafusion_common::tree_node::{TreeNode, TreeNodeRecursion};
718
719    let inner_exprs = inner.as_ref();
720
721    let mut ref_counts = vec![0usize; inner_exprs.len()];
722    for proj_expr in outer.as_ref() {
723        proj_expr
724            .expr
725            .apply(|e| {
726                if let Some(col) = e.as_ref().downcast_ref::<Column>()
727                    && let Some(count) = ref_counts.get_mut(col.index())
728                {
729                    *count += 1;
730                }
731                Ok(TreeNodeRecursion::Continue)
732            })
733            .expect("infallible closure should not fail");
734    }
735
736    ref_counts.iter().enumerate().any(|(idx, &count)| {
737        let expr = &inner_exprs[idx].expr;
738        count > 1 && (is_volatile(expr) || !expr.placement().should_push_to_leaves())
739    })
740}
741
742impl DataSource for FileScanConfig {
743    fn open(
744        &self,
745        partition: usize,
746        context: Arc<TaskContext>,
747    ) -> Result<SendableRecordBatchStream> {
748        self.open_with_args(OpenArgs::new(partition, context))
749    }
750
751    fn open_with_args(&self, args: OpenArgs) -> Result<SendableRecordBatchStream> {
752        let OpenArgs {
753            partition,
754            context,
755            sibling_state,
756        } = args;
757        let object_store = context.runtime_env().object_store(&self.object_store_url)?;
758        let batch_size = self
759            .batch_size
760            .unwrap_or_else(|| context.session_config().batch_size());
761
762        let source = self.file_source.with_batch_size(batch_size);
763
764        let morselizer = source.create_morselizer(object_store, self, partition)?;
765
766        // Extract the shared work source from the sibling state if it exists.
767        // This allows multiple sibling streams to steal work from a single
768        // shared queue of unopened files.
769        let shared_work_source = sibling_state
770            .as_ref()
771            .and_then(|state| state.downcast_ref::<SharedWorkSource>())
772            .cloned();
773
774        let stream = FileStreamBuilder::new(self)
775            .with_partition(partition)
776            .with_shared_work_source(shared_work_source)
777            .with_morselizer(morselizer)
778            .with_metrics(source.metrics())
779            .build()?;
780        Ok(Box::pin(cooperative(stream)))
781    }
782
783    fn fmt_as(&self, t: DisplayFormatType, f: &mut Formatter) -> FmtResult {
784        match t {
785            DisplayFormatType::Default | DisplayFormatType::Verbose => {
786                let schema = self.projected_schema().map_err(|_| std::fmt::Error {})?;
787                let orderings =
788                    sort_pushdown::get_projected_output_ordering(self, &schema);
789
790                write!(f, "file_groups=")?;
791                FileGroupsDisplay(&self.file_groups).fmt_as(t, f)?;
792
793                if !schema.fields().is_empty() {
794                    if let Some(projection) = self.file_source.projection() {
795                        // This matches what ProjectionExec does.
796                        // TODO: can we put this into ProjectionExprs so that it's shared code?
797                        let expr: Vec<String> = projection
798                            .as_ref()
799                            .iter()
800                            .map(|proj_expr| {
801                                if let Some(column) =
802                                    proj_expr.expr.downcast_ref::<Column>()
803                                {
804                                    if column.name() == proj_expr.alias {
805                                        column.name().to_string()
806                                    } else {
807                                        format!(
808                                            "{} as {}",
809                                            proj_expr.expr, proj_expr.alias
810                                        )
811                                    }
812                                } else {
813                                    format!("{} as {}", proj_expr.expr, proj_expr.alias)
814                                }
815                            })
816                            .collect();
817                        write!(f, ", projection=[{}]", expr.join(", "))?;
818                    } else {
819                        write!(f, ", projection={}", ProjectSchemaDisplay(&schema))?;
820                    }
821                }
822
823                if let Some(limit) = self.limit {
824                    write!(f, ", limit={limit}")?;
825                }
826
827                display_orderings(f, &orderings)?;
828
829                if self.output_partitioning.is_some() {
830                    write!(f, ", output_partitioning={}", self.output_partitioning())?;
831                }
832
833                if !self.constraints.is_empty() {
834                    write!(f, ", {}", self.constraints)?;
835                }
836
837                self.fmt_file_source(t, f)
838            }
839            DisplayFormatType::TreeRender => {
840                writeln!(f, "format={}", self.file_source.file_type())?;
841                self.file_source.fmt_extra(t, f)?;
842                let num_files = self.file_groups.iter().map(|fg| fg.len()).sum::<usize>();
843                writeln!(f, "files={num_files}")?;
844                Ok(())
845            }
846        }
847    }
848
849    /// If supported by the underlying [`FileSource`], redistribute files across partitions according to their size.
850    fn repartitioned(
851        &self,
852        target_partitions: usize,
853        repartition_file_min_size: usize,
854        output_ordering: Option<LexOrdering>,
855    ) -> Result<Option<Arc<dyn DataSource>>> {
856        // When file groups define output partitioning, repartitioning files
857        // would invalidate the partition-to-file-group mapping.
858        if self.output_partitioning.is_some() {
859            return Ok(None);
860        }
861
862        // An ordered scan can use the size-balanced split of an unordered
863        // scan when every new group is still sorted. That split keeps the
864        // files in group order and only moves the group boundaries, so groups
865        // like `[f1, f2], [f3, f4]` with a large `f1` become
866        // `[f1 head], [f1 tail, f2], ...`.
867        if output_ordering.is_some()
868            && let Some(balanced) = self.file_source.repartitioned(
869                target_partitions,
870                repartition_file_min_size,
871                None,
872                self,
873            )?
874            && balanced.validated_output_ordering() == self.validated_output_ordering()
875        {
876            return Ok(Some(Arc::new(balanced)));
877        }
878
879        let source = self.file_source.repartitioned(
880            target_partitions,
881            repartition_file_min_size,
882            output_ordering,
883            self,
884        )?;
885
886        Ok(source.map(|s| Arc::new(s) as _))
887    }
888
889    /// Returns the output partitioning for this file scan.
890    ///
891    /// When `output_partitioning` is set, this returns the declared partitioning
892    /// after applying scan projection, allowing the optimizer to skip hash
893    /// repartitioning for aggregates and joins on the partitioning columns.
894    ///
895    /// If projection or partition count validation fails, this returns
896    /// `UnknownPartitioning`.
897    ///
898    /// Tradeoffs
899    /// - Benefit: Eliminates `RepartitionExec` and `SortExec` for queries whose
900    ///   required distribution is satisfied by the scan's output partitioning.
901    /// - Cost: Files are grouped by partition values rather than split by byte
902    ///   ranges, which may reduce I/O parallelism when partition sizes are uneven.
903    ///   For simple aggregations without `ORDER BY`, this cost may outweigh the benefit.
904    ///
905    /// Follow-up Work
906    /// - Idea: Could allow byte-range splitting within partition-aware groups,
907    ///   preserving I/O parallelism while maintaining partition semantics.
908    fn output_partitioning(&self) -> Partitioning {
909        let Some(output_partitioning) = self.output_partitioning.clone() else {
910            return Partitioning::UnknownPartitioning(self.file_groups.len());
911        };
912        if output_partitioning.partition_count() != self.file_groups.len() {
913            warn!(
914                "Declared output partitioning has {} partitions, but file scan has {} file groups. Falling back to UnknownPartitioning.",
915                output_partitioning.partition_count(),
916                self.file_groups.len()
917            );
918            return Partitioning::UnknownPartitioning(self.file_groups.len());
919        }
920
921        if let Some(projection) = self.file_source.projection() {
922            let schema = self.file_source.table_schema().table_schema();
923            return match projection.projection_mapping(schema) {
924                Ok(mapping) => project_output_partitioning(
925                    &output_partitioning,
926                    &mapping,
927                    schema,
928                    self.file_groups.len(),
929                ),
930                Err(e) => {
931                    debug!(
932                        "Could not project output partitioning, falling back to UnknownPartitioning: {e}"
933                    );
934                    Partitioning::UnknownPartitioning(self.file_groups.len())
935                }
936            };
937        }
938
939        output_partitioning
940    }
941
942    /// Computes the effective equivalence properties of this file scan, taking
943    /// into account the file schema, any projections or filters applied by the
944    /// file source, and the output ordering.
945    fn eq_properties(&self) -> EquivalenceProperties {
946        let schema = self.file_source.table_schema().table_schema();
947        let mut eq_properties = EquivalenceProperties::new_with_orderings(
948            Arc::clone(schema),
949            self.validated_output_ordering(),
950        )
951        .with_constraints(self.constraints.clone());
952
953        // Only a filter that the source applies exactly gives valid equivalences.
954        // A filter that is used only for pruning lets non-matching rows through.
955        if let Some(filter) = self.file_source.exact_filter() {
956            // We need to remap column indexes to match the projected schema since that's what the equivalence properties deal with.
957            // Note that this will *ignore* any non-projected columns: these don't factor into ordering / equivalence.
958            match Self::add_filter_equivalence_info(&filter, &mut eq_properties, schema) {
959                Ok(()) => {}
960                Err(e) => {
961                    warn!("Failed to add filter equivalence info: {e}");
962                    #[cfg(debug_assertions)]
963                    panic!("Failed to add filter equivalence info: {e}");
964                }
965            }
966        }
967
968        if let Some(projection) = self.file_source.projection() {
969            match (
970                projection.project_schema(schema),
971                projection.projection_mapping(schema),
972            ) {
973                (Ok(output_schema), Ok(mapping)) => {
974                    eq_properties =
975                        eq_properties.project(&mapping, Arc::new(output_schema));
976                }
977                (Err(e), _) | (_, Err(e)) => {
978                    warn!("Failed to project equivalence properties: {e}");
979                    #[cfg(debug_assertions)]
980                    panic!("Failed to project equivalence properties: {e}");
981                }
982            }
983        }
984
985        eq_properties
986    }
987
988    fn scheduling_type(&self) -> SchedulingType {
989        SchedulingType::Cooperative
990    }
991
992    fn partition_statistics(&self, partition: Option<usize>) -> Result<Arc<Statistics>> {
993        if let Some(partition) = partition {
994            // Get statistics for a specific partition
995            // Note: FileGroup statistics include partition columns (computed from partition_values)
996            if let Some(file_group) = self.file_groups.get(partition)
997                && let Some(stat) = file_group.file_statistics(None)
998            {
999                // Project the statistics based on the projection
1000                let output_schema = self.projected_schema()?;
1001                return if let Some(projection) = self.file_source.projection() {
1002                    Ok(Arc::new(projection.project_statistics_with_input_schema(
1003                        stat.clone(),
1004                        self.file_source.table_schema().table_schema(),
1005                        &output_schema,
1006                    )?))
1007                } else {
1008                    Ok(Arc::new(stat.clone()))
1009                };
1010            }
1011            // If no statistics available for this partition, return unknown
1012            Ok(Arc::new(Statistics::new_unknown(
1013                self.projected_schema()?.as_ref(),
1014            )))
1015        } else {
1016            // Return aggregate statistics across all partitions
1017            let statistics = self.statistics();
1018            let projection = self.file_source.projection();
1019            let output_schema = self.projected_schema()?;
1020            if let Some(projection) = &projection {
1021                Ok(Arc::new(projection.project_statistics_with_input_schema(
1022                    statistics.clone(),
1023                    self.file_source.table_schema().table_schema(),
1024                    &output_schema,
1025                )?))
1026            } else {
1027                Ok(Arc::new(statistics))
1028            }
1029        }
1030    }
1031
1032    fn with_fetch(&self, limit: Option<usize>) -> Option<Arc<dyn DataSource>> {
1033        let source = FileScanConfigBuilder::from(self.clone())
1034            .with_limit(limit)
1035            .build();
1036        Some(Arc::new(source))
1037    }
1038
1039    fn fetch(&self) -> Option<usize> {
1040        self.limit
1041    }
1042
1043    fn metrics(&self) -> ExecutionPlanMetricsSet {
1044        self.file_source.metrics().clone()
1045    }
1046
1047    fn try_swapping_with_projection(
1048        &self,
1049        projection: &ProjectionExprs,
1050    ) -> Result<Option<Arc<dyn DataSource>>> {
1051        // Don't merge a projection into the scan if it would inline a volatile
1052        // or expensive expression referenced more than once. For a volatile
1053        // expression (e.g. `random()` aliased in a subquery) this would turn a
1054        // single "locked-in" value into multiple independent evaluations (see
1055        // #23220); for an expensive scalar function it would undo CSE and
1056        // re-evaluate the expression at every reference site.
1057        if let Some(inner) = self.file_source.projection()
1058            && would_duplicate_costly_exprs(inner, projection)
1059        {
1060            return Ok(None);
1061        }
1062        match self.file_source.try_pushdown_projection(projection)? {
1063            Some(new_source) => {
1064                let mut new_file_scan_config = self.clone();
1065                new_file_scan_config.file_source = new_source;
1066                Ok(Some(Arc::new(new_file_scan_config) as Arc<dyn DataSource>))
1067            }
1068            None => Ok(None),
1069        }
1070    }
1071
1072    fn try_pushdown_filters(
1073        &self,
1074        filters: Vec<Arc<dyn PhysicalExpr>>,
1075        config: &ConfigOptions,
1076    ) -> Result<FilterPushdownPropagation<Arc<dyn DataSource>>> {
1077        // Remap filter Column indices to match the table schema (file + partition columns).
1078        // This is necessary because filters refer to the output schema of this `DataSource`
1079        // (e.g., after projection pushdown has been applied) and need to be remapped to the table schema
1080        // before being passed to the file source
1081        //
1082        // For example, consider a filter `c1_c2 > 5` being pushed down. If the
1083        // `DataSource` has a projection `c1 + c2 as c1_c2`, the filter must be rewritten
1084        // to refer to the table schema `c1 + c2 > 5`
1085        let table_schema = self.file_source.table_schema().table_schema();
1086        let filters_to_remap = if let Some(projection) = self.file_source.projection() {
1087            filters
1088                .into_iter()
1089                .map(|filter| projection.unproject_expr(&filter))
1090                .collect::<Result<Vec<_>>>()?
1091        } else {
1092            filters
1093        };
1094        // Now remap column indices to match the table schema.
1095        let remapped_filters = filters_to_remap
1096            .into_iter()
1097            .map(|filter| reassign_expr_columns(filter, table_schema))
1098            .collect::<Result<Vec<_>>>()?;
1099
1100        let result = self
1101            .file_source
1102            .try_pushdown_filters(remapped_filters, config)?;
1103        match result.updated_node {
1104            Some(new_file_source) => {
1105                let mut new_file_scan_config = self.clone();
1106                new_file_scan_config.file_source = new_file_source;
1107                Ok(FilterPushdownPropagation {
1108                    filters: result.filters,
1109                    updated_node: Some(Arc::new(new_file_scan_config) as _),
1110                })
1111            }
1112            None => {
1113                // If the file source does not support filter pushdown, return the original config
1114                Ok(FilterPushdownPropagation {
1115                    filters: result.filters,
1116                    updated_node: None,
1117                })
1118            }
1119        }
1120    }
1121
1122    /// Push sort requirements into file-based data sources.
1123    ///
1124    /// # Sort Pushdown Architecture
1125    ///
1126    /// When a partition (file group) contains multiple files in wrong order,
1127    /// `validated_output_ordering()` strips the ordering and `EnforceSorting`
1128    /// inserts a `SortExec`. This optimizer fixes the file order by sorting
1129    /// files within each group by min/max statistics, enabling sort elimination.
1130    ///
1131    /// This applies to both single-partition and multi-partition plans — any
1132    /// file group with multiple files in wrong order benefits.
1133    ///
1134    /// ```text
1135    /// PushdownSort optimizer finds SortExec
1136    ///   │
1137    ///   ▼
1138    /// FileScanConfig::try_pushdown_sort()
1139    ///   │
1140    ///   ├─► FileSource returns Exact
1141    ///   │     (natural ordering satisfies request)
1142    ///   │     → rebuild_with_source: sort files by stats, verify non-overlapping
1143    ///   │     → SortExec removed, fetch (LIMIT) pushed to DataSourceExec
1144    ///   │
1145    ///   ├─► FileSource returns Inexact
1146    ///   │     (e.g. column_in_file_schema: opener will reorder RGs at runtime)
1147    ///   │     → rebuild_with_source: sort files by stats; if the post-sort
1148    ///   │       file groups are non-overlapping AND the request now validates
1149    ///   │       AND no NULLs sit in the sort columns of non-last files,
1150    ///   │       upgrade back to Exact (SortExec removed). Otherwise stays
1151    ///   │       Inexact and SortExec is kept while the scan is still
1152    ///   │       optimised via `sort_order_for_reorder` / `reverse_row_groups`.
1153    ///   │
1154    ///   └─► FileSource returns Unsupported
1155    ///         (e.g. expression sort key or partition column)
1156    ///         → try_sort_file_groups_by_statistics():
1157    ///           1. Sort files within each group by min/max statistics
1158    ///           2. Re-check: non-overlapping + ordering valid + no NULLs?
1159    ///              YES → Exact → SortExec removed
1160    ///              NO  → Inexact (files reordered, Sort stays)
1161    /// ```
1162    fn try_pushdown_sort(
1163        &self,
1164        order: &[PhysicalSortExpr],
1165    ) -> Result<SortOrderPushdownResult<Arc<dyn DataSource>>> {
1166        let pushdown_result = self
1167            .file_source
1168            .try_pushdown_sort(order, &self.eq_properties())?;
1169
1170        match pushdown_result {
1171            SortOrderPushdownResult::Exact { inner } => {
1172                let config = self.rebuild_with_source(inner, true, order)?;
1173                // rebuild_with_source keeps output_ordering only when all groups
1174                // are non-overlapping. If output_ordering was cleared, files
1175                // overlap despite within-file ordering → downgrade to Inexact.
1176                if config.output_ordering.is_empty() {
1177                    Ok(SortOrderPushdownResult::Inexact {
1178                        inner: Arc::new(config),
1179                    })
1180                } else {
1181                    Ok(SortOrderPushdownResult::Exact {
1182                        inner: Arc::new(config),
1183                    })
1184                }
1185            }
1186            SortOrderPushdownResult::Inexact { inner } => {
1187                let mut config = self.rebuild_with_source(inner, false, order)?;
1188                // `rebuild_with_source` reorders files by stats; if the
1189                // post-sort files are non-overlapping AND the request now
1190                // validates against the new file groups, `output_ordering`
1191                // is preserved and we can upgrade back to Exact. This
1192                // restores the sort-elimination behaviour that lived in
1193                // the `Unsupported` → `try_sort_file_groups_by_statistics`
1194                // path before #21956 routed `column_in_file_schema` cases
1195                // here.
1196                if config.output_ordering.is_empty() {
1197                    return Ok(SortOrderPushdownResult::Inexact {
1198                        inner: Arc::new(config),
1199                    });
1200                }
1201                // Upgrading to Exact: the post-sort file groups are
1202                // non-overlapping and each file's declared ordering
1203                // re-validates, so reading the files in their natural
1204                // (declared-sorted) order already yields the requested
1205                // ordering — exactly like the `Unsupported` → Exact path,
1206                // which reads files in natural order too.
1207                //
1208                // Drop the runtime row-group reorder hints the Inexact
1209                // source carried (`sort_order_for_reorder` /
1210                // `reverse_row_groups`) by restoring the original,
1211                // hint-free source. With the `SortExec` removed those
1212                // hints are not just redundant but unsafe: for a DESC
1213                // request the opener sorts row groups ASC-by-min and then
1214                // reverses them, which reorders two row groups within a
1215                // single file that share the same `min` incorrectly
1216                // (e.g. a file `[10,8,8,8]` whose row groups are
1217                // `[10,8]` and `[8,8]` would stream as `8,8,10,8`).
1218                // The `SortExec` used to mask this; once it is gone the
1219                // reordered stream is the final, wrong answer.
1220                config.file_source = Arc::clone(&self.file_source);
1221                Ok(SortOrderPushdownResult::Exact {
1222                    inner: Arc::new(config),
1223                })
1224            }
1225            SortOrderPushdownResult::Unsupported => {
1226                self.try_sort_file_groups_by_statistics(order)
1227            }
1228        }
1229    }
1230
1231    fn apply_expressions(
1232        &self,
1233        f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
1234    ) -> Result<TreeNodeRecursion> {
1235        // Delegate to the file source
1236        self.file_source.apply_expressions(f)
1237    }
1238
1239    /// Create any shared state that should be passed between sibling streams
1240    /// during one execution.
1241    ///
1242    /// This returns `None` when sibling streams must not share work, such as
1243    /// when file order must be preserved, the file groups define the output
1244    /// partitioning needed for the rest of the plan, or work stealing is
1245    /// disabled via
1246    /// `datafusion.execution.enable_file_stream_work_stealing`.
1247    fn create_sibling_state(
1248        &self,
1249        config: &ConfigOptions,
1250    ) -> Option<Arc<dyn Any + Send + Sync>> {
1251        if self.preserves_file_order()
1252            || self.output_partitioning.is_some()
1253            || !config.execution.enable_file_stream_work_stealing
1254        {
1255            return None;
1256        }
1257
1258        Some(Arc::new(SharedWorkSource::from_config(self)) as Arc<dyn Any + Send + Sync>)
1259    }
1260
1261    /// Serialize this file scan by delegating to the concrete
1262    /// [`FileSource`]'s
1263    /// [`try_to_proto`](crate::file::FileSource::try_to_proto) hook, passing
1264    /// `self` as the shared spine it needs to emit the base config.
1265    #[cfg(feature = "proto")]
1266    fn try_to_proto(
1267        &self,
1268        ctx: &datafusion_physical_plan::proto::ExecutionPlanEncodeCtx<'_>,
1269    ) -> Result<Option<datafusion_proto_models::protobuf::PhysicalPlanNode>> {
1270        self.file_source().try_to_proto(self, ctx)
1271    }
1272}
1273
1274/// Separates files that require statistics reasoning from files proven empty.
1275///
1276/// The latter must remain in the scan even though they cannot affect ordering.
1277fn partition_known_empty_files<'a>(
1278    files: impl IntoIterator<Item = &'a PartitionedFile>,
1279) -> (Vec<&'a PartitionedFile>, Vec<&'a PartitionedFile>) {
1280    files
1281        .into_iter()
1282        .partition(|file| !file.statistics.as_deref().is_some_and(is_known_empty))
1283}
1284
1285/// Appends empty files to the smallest groups without affecting their row order.
1286fn append_known_empty_files(
1287    file_groups: &mut [FileGroup],
1288    empty_files: Vec<&PartitionedFile>,
1289) {
1290    for file in empty_files {
1291        file_groups
1292            .iter_mut()
1293            .min_by_key(|group| group.len())
1294            .expect("non-empty files must create at least one file group")
1295            .push((*file).clone());
1296    }
1297}
1298
1299impl FileScanConfig {
1300    /// Returns true if files must be read in the order of the file groups.
1301    ///
1302    /// Parents such as `SortPreservingMergeExec` rely on the output ordering
1303    /// this scan advertises, so a scan with an output ordering never shares
1304    /// files between partitions (work stealing) and never skips rows based on
1305    /// its limit (limit pruning).
1306    pub fn preserves_file_order(&self) -> bool {
1307        self.preserve_order || !self.output_ordering.is_empty()
1308    }
1309
1310    /// Returns only the output orderings that are validated against actual
1311    /// file group statistics.
1312    ///
1313    /// For example, individual files may be ordered by `col1 ASC`,
1314    /// but if we have files with these min/max statistics in a single partition / file group:
1315    ///
1316    /// - file1: min(col1) = 10, max(col1) = 20
1317    /// - file2: min(col1) = 5, max(col1) = 15
1318    ///
1319    /// Because reading file1 followed by file2 would produce out-of-order output (there is overlap
1320    /// in the ranges), we cannot retain `col1 ASC` as a valid output ordering.
1321    ///
1322    /// Similarly this would not be a valid order (non-overlapping ranges but not ordered):
1323    ///
1324    /// - file1: min(col1) = 20, max(col1) = 30
1325    /// - file2: min(col1) = 10, max(col1) = 15
1326    ///
1327    /// On the other hand if we had:
1328    ///
1329    /// - file1: min(col1) = 5, max(col1) = 15
1330    /// - file2: min(col1) = 16, max(col1) = 25
1331    ///
1332    /// Then we know that reading file1 followed by file2 will produce ordered output,
1333    /// so `col1 ASC` would be retained.
1334    ///
1335    /// Note that we are checking for ordering *within* *each* file group / partition,
1336    /// files in different partitions are read independently and do not affect each other's ordering.
1337    /// Merging of the multiple partition streams into a single ordered stream is handled
1338    /// upstream e.g. by `SortPreservingMergeExec`.
1339    fn validated_output_ordering(&self) -> Vec<LexOrdering> {
1340        let schema = self.file_source.table_schema().table_schema();
1341        sort_pushdown::validate_orderings(
1342            &self.output_ordering,
1343            schema,
1344            &self.file_groups,
1345            None,
1346        )
1347    }
1348
1349    /// Get the file schema (schema of the files without partition columns)
1350    pub fn file_schema(&self) -> &SchemaRef {
1351        self.file_source.table_schema().file_schema()
1352    }
1353
1354    /// Get the table partition columns
1355    pub fn table_partition_cols(&self) -> &Fields {
1356        self.file_source.table_schema().table_partition_cols()
1357    }
1358
1359    /// Returns the unprojected table statistics, marking them as inexact if filters are present.
1360    ///
1361    /// When filters are pushed down (including pruning predicates and bloom filters),
1362    /// we can't guarantee the statistics are exact because we don't know how many
1363    /// rows will be filtered out.
1364    pub fn statistics(&self) -> Statistics {
1365        let filter_may_change_row_count = self.file_source.filter().is_some()
1366            && self.statistics.num_rows != Precision::Exact(0);
1367        if filter_may_change_row_count {
1368            self.statistics.clone().to_inexact()
1369        } else {
1370            self.statistics.clone()
1371        }
1372    }
1373
1374    pub fn projected_schema(&self) -> Result<Arc<Schema>> {
1375        let schema = self.file_source.table_schema().table_schema();
1376        match self.file_source.projection() {
1377            Some(proj) => Ok(Arc::new(proj.project_schema(schema)?)),
1378            None => Ok(Arc::clone(schema)),
1379        }
1380    }
1381
1382    fn add_filter_equivalence_info(
1383        filter: &Arc<dyn PhysicalExpr>,
1384        eq_properties: &mut EquivalenceProperties,
1385        schema: &Schema,
1386    ) -> Result<()> {
1387        // Gather valid equality pairs from the filter expression
1388        let equal_pairs = split_conjunction(filter).into_iter().filter_map(|expr| {
1389            // Ignore any binary expressions that reference non-existent columns in the current schema
1390            // (e.g. due to unnecessary projections being removed)
1391            reassign_expr_columns(Arc::clone(expr), schema)
1392                .ok()
1393                .and_then(|expr| match expr.downcast_ref::<BinaryExpr>() {
1394                    Some(expr) if expr.op() == &Operator::Eq => {
1395                        Some((Arc::clone(expr.left()), Arc::clone(expr.right())))
1396                    }
1397                    _ => None,
1398                })
1399        });
1400
1401        for (lhs, rhs) in equal_pairs {
1402            eq_properties.add_equal_conditions(lhs, rhs)?
1403        }
1404
1405        Ok(())
1406    }
1407
1408    /// Returns whether newlines in values are supported.
1409    ///
1410    /// This method always returns `false`. The actual newlines_in_values setting
1411    /// has been moved to [`CsvSource`] and should be accessed via
1412    /// [`CsvSource::csv_options()`] instead.
1413    ///
1414    /// [`CsvSource`]: https://docs.rs/datafusion/latest/datafusion/datasource/physical_plan/struct.CsvSource.html
1415    /// [`CsvSource::csv_options()`]: https://docs.rs/datafusion/latest/datafusion/datasource/physical_plan/struct.CsvSource.html#method.csv_options
1416    #[deprecated(
1417        since = "52.0.0",
1418        note = "newlines_in_values has moved to CsvSource. Access it via CsvSource::csv_options().newlines_in_values instead. It will be removed in 58.0.0 or 6 months after 52.0.0 is released, whichever comes first."
1419    )]
1420    pub fn newlines_in_values(&self) -> bool {
1421        false
1422    }
1423
1424    #[deprecated(
1425        since = "52.0.0",
1426        note = "This method is no longer used, use eq_properties instead. It will be removed in 58.0.0 or 6 months after 52.0.0 is released, whichever comes first."
1427    )]
1428    pub fn projected_constraints(&self) -> Constraints {
1429        let props = self.eq_properties();
1430        props.constraints().clone()
1431    }
1432
1433    #[deprecated(
1434        since = "52.0.0",
1435        note = "This method is no longer used, use eq_properties instead. It will be removed in 58.0.0 or 6 months after 52.0.0 is released, whichever comes first."
1436    )]
1437    pub fn file_column_projection_indices(&self) -> Option<Vec<usize>> {
1438        #[expect(deprecated)]
1439        self.file_source.projection().as_ref().map(|p| {
1440            p.ordered_column_indices()
1441                .into_iter()
1442                .filter(|&i| i < self.file_schema().fields().len())
1443                .collect::<Vec<_>>()
1444        })
1445    }
1446
1447    /// Splits file groups into new groups based on statistics to enable efficient parallel processing.
1448    ///
1449    /// The method distributes files across a target number of partitions while ensuring
1450    /// files within each partition maintain sort order based on their min/max statistics.
1451    ///
1452    /// The algorithm works by:
1453    /// 1. Takes files sorted by minimum values
1454    /// 2. For each file:
1455    ///   - Finds eligible groups (empty or where file's min > group's last max)
1456    ///   - Selects the smallest eligible group
1457    ///   - Creates a new group if needed
1458    ///
1459    /// # Parameters
1460    /// * `table_schema`: Schema containing information about the columns
1461    /// * `file_groups`: The original file groups to split
1462    /// * `sort_order`: The lexicographical ordering to maintain within each group
1463    /// * `target_partitions`: The desired number of output partitions
1464    ///
1465    /// # Returns
1466    /// A new set of file groups, where files within each group are non-overlapping with respect to
1467    /// their min/max statistics and maintain the specified sort order.
1468    pub fn split_groups_by_statistics_with_target_partitions(
1469        table_schema: &SchemaRef,
1470        file_groups: &[FileGroup],
1471        sort_order: &LexOrdering,
1472        target_partitions: usize,
1473    ) -> Result<Vec<FileGroup>> {
1474        if target_partitions == 0 {
1475            return Err(internal_datafusion_err!(
1476                "target_partitions must be greater than 0"
1477            ));
1478        }
1479
1480        let flattened_files = file_groups
1481            .iter()
1482            .flat_map(FileGroup::iter)
1483            .collect::<Vec<_>>();
1484
1485        if flattened_files.is_empty() {
1486            return Ok(vec![]);
1487        }
1488
1489        let (files, empty_files) = partition_known_empty_files(flattened_files);
1490        if files.is_empty() {
1491            return Ok(file_groups.to_vec());
1492        }
1493
1494        let statistics = MinMaxStatistics::new_from_files(
1495            sort_order,
1496            table_schema,
1497            None,
1498            files.iter().copied(),
1499        )?;
1500
1501        let indices_sorted_by_min = statistics.min_values_sorted();
1502
1503        // Initialize with target_partitions empty groups
1504        let mut file_groups_indices: Vec<Vec<usize>> = vec![vec![]; target_partitions];
1505
1506        for (idx, min) in indices_sorted_by_min {
1507            if let Some((_, group)) = file_groups_indices
1508                .iter_mut()
1509                .enumerate()
1510                .filter(|(_, group)| {
1511                    group.is_empty()
1512                        || min
1513                            > statistics
1514                                .max(*group.last().expect("groups should not be empty"))
1515                })
1516                .min_by_key(|(_, group)| group.len())
1517            {
1518                group.push(idx);
1519            } else {
1520                // Create a new group if no existing group fits
1521                file_groups_indices.push(vec![idx]);
1522            }
1523        }
1524
1525        // Remove any empty groups
1526        file_groups_indices.retain(|group| !group.is_empty());
1527
1528        // Assemble indices back into groups of PartitionedFiles
1529        let mut file_groups = file_groups_indices
1530            .into_iter()
1531            .map(|file_group_indices| {
1532                FileGroup::new(
1533                    file_group_indices
1534                        .into_iter()
1535                        .map(|idx| files[idx].clone())
1536                        .collect(),
1537                )
1538            })
1539            .collect::<Vec<_>>();
1540
1541        append_known_empty_files(&mut file_groups, empty_files);
1542        Ok(file_groups)
1543    }
1544
1545    /// Attempts to do a bin-packing on files into file groups, such that any two files
1546    /// in a file group are ordered and non-overlapping with respect to their statistics.
1547    /// It will produce the smallest number of file groups possible.
1548    pub fn split_groups_by_statistics(
1549        table_schema: &SchemaRef,
1550        file_groups: &[FileGroup],
1551        sort_order: &LexOrdering,
1552    ) -> Result<Vec<FileGroup>> {
1553        let flattened_files = file_groups
1554            .iter()
1555            .flat_map(FileGroup::iter)
1556            .collect::<Vec<_>>();
1557        // First Fit:
1558        // * Choose the first file group that a file can be placed into.
1559        // * If it fits into no existing file groups, create a new one.
1560        //
1561        // By sorting files by min values and then applying first-fit bin packing,
1562        // we can produce the smallest number of file groups such that
1563        // files within a group are in order and non-overlapping.
1564        //
1565        // Source: Applied Combinatorics (Keller and Trotter), Chapter 6.8
1566        // https://www.appliedcombinatorics.org/book/s_posets_dilworth-intord.html
1567
1568        if flattened_files.is_empty() {
1569            return Ok(vec![]);
1570        }
1571
1572        let (files, empty_files) = partition_known_empty_files(flattened_files);
1573        if files.is_empty() {
1574            return Ok(file_groups.to_vec());
1575        }
1576
1577        let statistics = MinMaxStatistics::new_from_files(
1578            sort_order,
1579            table_schema,
1580            None,
1581            files.iter().copied(),
1582        )
1583        .map_err(|e| {
1584            e.context("construct min/max statistics for split_groups_by_statistics")
1585        })?;
1586
1587        let indices_sorted_by_min = statistics.min_values_sorted();
1588        let mut file_groups_indices: Vec<Vec<usize>> = vec![];
1589
1590        for (idx, min) in indices_sorted_by_min {
1591            let file_group_to_insert = file_groups_indices.iter_mut().find(|group| {
1592                // If our file is non-overlapping and comes _after_ the last file,
1593                // it fits in this file group.
1594                min > statistics.max(
1595                    *group
1596                        .last()
1597                        .expect("groups should be nonempty at construction"),
1598                )
1599            });
1600            match file_group_to_insert {
1601                Some(group) => group.push(idx),
1602                None => file_groups_indices.push(vec![idx]),
1603            }
1604        }
1605
1606        // Assemble indices back into groups of PartitionedFiles
1607        let mut file_groups = file_groups_indices
1608            .into_iter()
1609            .map(|file_group_indices| {
1610                file_group_indices
1611                    .into_iter()
1612                    .map(|idx| files[idx].clone())
1613                    .collect::<FileGroup>()
1614            })
1615            .collect::<Vec<_>>();
1616
1617        append_known_empty_files(&mut file_groups, empty_files);
1618        Ok(file_groups)
1619    }
1620
1621    /// Write the data_type based on file_source
1622    fn fmt_file_source(&self, t: DisplayFormatType, f: &mut Formatter) -> FmtResult {
1623        write!(f, ", file_type={}", self.file_source.file_type())?;
1624        self.file_source.fmt_extra(t, f)
1625    }
1626
1627    /// Returns the file_source
1628    pub fn file_source(&self) -> &Arc<dyn FileSource> {
1629        &self.file_source
1630    }
1631
1632    // Sort pushdown methods (rebuild_with_source, try_sort_file_groups_by_statistics,
1633    // sort_files_within_groups_by_statistics, any_file_has_nulls_in_sort_columns)
1634    // are in crate::sort_pushdown module.
1635}
1636
1637impl Debug for FileScanConfig {
1638    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
1639        write!(f, "FileScanConfig {{")?;
1640        write!(f, "object_store_url={:?}, ", self.object_store_url)?;
1641
1642        write!(f, "statistics={:?}, ", self.statistics())?;
1643
1644        DisplayAs::fmt_as(self, DisplayFormatType::Verbose, f)?;
1645        write!(f, "}}")
1646    }
1647}
1648
1649impl DisplayAs for FileScanConfig {
1650    fn fmt_as(&self, t: DisplayFormatType, f: &mut Formatter) -> FmtResult {
1651        let schema = self.projected_schema().map_err(|_| std::fmt::Error {})?;
1652        let orderings = sort_pushdown::get_projected_output_ordering(self, &schema);
1653
1654        write!(f, "file_groups=")?;
1655        FileGroupsDisplay(&self.file_groups).fmt_as(t, f)?;
1656
1657        if !schema.fields().is_empty() {
1658            write!(f, ", projection={}", ProjectSchemaDisplay(&schema))?;
1659        }
1660
1661        if let Some(limit) = self.limit {
1662            write!(f, ", limit={limit}")?;
1663        }
1664
1665        display_orderings(f, &orderings)?;
1666
1667        if !self.constraints.is_empty() {
1668            write!(f, ", {}", self.constraints)?;
1669        }
1670
1671        Ok(())
1672    }
1673}
1674
1675/// Convert type to a type suitable for use as a `ListingTable`
1676/// partition column. Returns `Dictionary(UInt16, val_type)`, which is
1677/// a reasonable trade off between a reasonable number of partition
1678/// values and space efficiency.
1679///
1680/// This use this to specify types for partition columns. However
1681/// you MAY also choose not to dictionary-encode the data or to use a
1682/// different dictionary type.
1683///
1684/// Use [`wrap_partition_value_in_dict`] to wrap a [`ScalarValue`] in the same say.
1685pub fn wrap_partition_type_in_dict(val_type: DataType) -> DataType {
1686    DataType::Dictionary(Box::new(DataType::UInt16), Box::new(val_type))
1687}
1688
1689/// Convert a [`ScalarValue`] of partition columns to a type, as
1690/// described in the documentation of [`wrap_partition_type_in_dict`],
1691/// which can wrap the types.
1692pub fn wrap_partition_value_in_dict(val: ScalarValue) -> ScalarValue {
1693    ScalarValue::Dictionary(Box::new(DataType::UInt16), Box::new(val))
1694}
1695
1696#[cfg(test)]
1697mod tests {
1698    use std::collections::HashMap;
1699
1700    use super::*;
1701    use crate::source::DataSourceExec;
1702    use crate::test_util::col;
1703    use crate::{TableSchema, TableSchemaBuilder};
1704    use crate::{
1705        generate_test_files, test_util::MockSource, tests::aggr_test_schema,
1706        verify_sort_integrity,
1707    };
1708
1709    use arrow::array::{Int32Array, RecordBatch};
1710    use arrow::datatypes::Field;
1711    use datafusion_common::ColumnStatistics;
1712    use datafusion_common::stats::Precision;
1713    use datafusion_common::tree_node::TreeNodeRecursion;
1714    use datafusion_common::{Result, assert_batches_eq, internal_err};
1715    use datafusion_execution::TaskContext;
1716    use datafusion_expr::SortExpr;
1717    use datafusion_physical_expr::PhysicalExpr;
1718
1719    #[cfg(feature = "proto")]
1720    use datafusion_expr::{AggregateUDF, ScalarUDF, WindowUDF};
1721    use datafusion_physical_expr::create_physical_sort_expr;
1722    use datafusion_physical_expr::expressions::Literal;
1723    use datafusion_physical_expr::projection::ProjectionExpr;
1724    use datafusion_physical_expr::projection::ProjectionExprs;
1725    use datafusion_physical_plan::ExecutionPlan;
1726    use datafusion_physical_plan::execution_plan::collect;
1727    #[cfg(feature = "proto")]
1728    use datafusion_physical_plan::proto::{ExecutionPlanEncode, ExecutionPlanEncodeCtx};
1729    #[cfg(feature = "proto")]
1730    use datafusion_proto_models::protobuf::{PhysicalExprNode, PhysicalPlanNode};
1731    use futures::FutureExt as _;
1732    use futures::StreamExt as _;
1733    use futures::stream;
1734    use object_store::ObjectStore;
1735    use std::fmt::Debug;
1736
1737    #[derive(Clone)]
1738    struct InexactSortPushdownSource {
1739        metrics: ExecutionPlanMetricsSet,
1740        table_schema: TableSchema,
1741    }
1742
1743    impl InexactSortPushdownSource {
1744        fn new(table_schema: TableSchema) -> Self {
1745            Self {
1746                metrics: ExecutionPlanMetricsSet::new(),
1747                table_schema,
1748            }
1749        }
1750    }
1751
1752    impl FileSource for InexactSortPushdownSource {
1753        fn create_file_opener(
1754            &self,
1755            _object_store: Arc<dyn ObjectStore>,
1756            _base_config: &FileScanConfig,
1757            _partition: usize,
1758        ) -> Result<Arc<dyn crate::file_stream::FileOpener>> {
1759            unimplemented!()
1760        }
1761
1762        fn table_schema(&self) -> &TableSchema {
1763            &self.table_schema
1764        }
1765
1766        fn with_batch_size(&self, _batch_size: usize) -> Arc<dyn FileSource> {
1767            Arc::new(self.clone())
1768        }
1769
1770        fn metrics(&self) -> &ExecutionPlanMetricsSet {
1771            &self.metrics
1772        }
1773
1774        fn file_type(&self) -> &str {
1775            "mock"
1776        }
1777
1778        fn try_pushdown_sort(
1779            &self,
1780            _order: &[PhysicalSortExpr],
1781            _eq_properties: &EquivalenceProperties,
1782        ) -> Result<SortOrderPushdownResult<Arc<dyn FileSource>>> {
1783            Ok(SortOrderPushdownResult::Inexact {
1784                inner: Arc::new(self.clone()) as Arc<dyn FileSource>,
1785            })
1786        }
1787
1788        fn apply_expressions(
1789            &self,
1790            _f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
1791        ) -> Result<TreeNodeRecursion> {
1792            Ok(TreeNodeRecursion::Continue)
1793        }
1794    }
1795
1796    #[cfg(feature = "proto")]
1797    #[derive(Clone)]
1798    struct ProtoHookSource {
1799        metrics: ExecutionPlanMetricsSet,
1800        table_schema: TableSchema,
1801    }
1802
1803    #[cfg(feature = "proto")]
1804    impl ProtoHookSource {
1805        fn new(table_schema: TableSchema) -> Self {
1806            Self {
1807                metrics: ExecutionPlanMetricsSet::new(),
1808                table_schema,
1809            }
1810        }
1811    }
1812
1813    #[cfg(feature = "proto")]
1814    impl FileSource for ProtoHookSource {
1815        fn create_file_opener(
1816            &self,
1817            _object_store: Arc<dyn ObjectStore>,
1818            _base_config: &FileScanConfig,
1819            _partition: usize,
1820        ) -> Result<Arc<dyn crate::file_stream::FileOpener>> {
1821            internal_err!("not needed for proto delegation test")
1822        }
1823
1824        fn table_schema(&self) -> &TableSchema {
1825            &self.table_schema
1826        }
1827
1828        fn with_batch_size(&self, _batch_size: usize) -> Arc<dyn FileSource> {
1829            Arc::new(self.clone())
1830        }
1831
1832        fn metrics(&self) -> &ExecutionPlanMetricsSet {
1833            &self.metrics
1834        }
1835
1836        fn file_type(&self) -> &str {
1837            "proto-hook-test"
1838        }
1839
1840        fn apply_expressions(
1841            &self,
1842            _f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
1843        ) -> Result<TreeNodeRecursion> {
1844            Ok(TreeNodeRecursion::Continue)
1845        }
1846
1847        fn try_to_proto(
1848            &self,
1849            _base: &FileScanConfig,
1850            _ctx: &ExecutionPlanEncodeCtx<'_>,
1851        ) -> Result<Option<PhysicalPlanNode>> {
1852            Ok(Some(PhysicalPlanNode::default()))
1853        }
1854    }
1855
1856    #[cfg(feature = "proto")]
1857    struct UnusedPlanEncoder;
1858
1859    #[cfg(feature = "proto")]
1860    impl ExecutionPlanEncode for UnusedPlanEncoder {
1861        fn encode_plan(
1862            &self,
1863            _plan: &Arc<dyn ExecutionPlan>,
1864        ) -> Result<PhysicalPlanNode> {
1865            internal_err!("not needed for proto delegation test")
1866        }
1867
1868        fn encode_expr(&self, _expr: &Arc<dyn PhysicalExpr>) -> Result<PhysicalExprNode> {
1869            internal_err!("not needed for proto delegation test")
1870        }
1871
1872        fn encode_udf(&self, _udf: &ScalarUDF) -> Result<Option<Vec<u8>>> {
1873            internal_err!("not needed for proto delegation test")
1874        }
1875
1876        fn encode_udaf(&self, _udaf: &AggregateUDF) -> Result<Option<Vec<u8>>> {
1877            internal_err!("not needed for proto delegation test")
1878        }
1879
1880        fn encode_udwf(&self, _udwf: &WindowUDF) -> Result<Option<Vec<u8>>> {
1881            internal_err!("not needed for proto delegation test")
1882        }
1883    }
1884
1885    #[cfg(feature = "proto")]
1886    #[test]
1887    fn data_source_exec_delegates_proto_to_file_source() -> Result<()> {
1888        let schema = Arc::new(Schema::new(vec![Field::new(
1889            "value",
1890            DataType::Int32,
1891            false,
1892        )]));
1893        let source = Arc::new(ProtoHookSource::new(TableSchema::from(&schema)));
1894        let config =
1895            FileScanConfigBuilder::new(ObjectStoreUrl::local_filesystem(), source)
1896                .build();
1897        let exec = DataSourceExec::from_data_source(config);
1898        let encoder = UnusedPlanEncoder;
1899        let ctx = ExecutionPlanEncodeCtx::new(&encoder);
1900
1901        assert_eq!(exec.try_to_proto(&ctx)?, Some(PhysicalPlanNode::default()));
1902        Ok(())
1903    }
1904
1905    #[test]
1906    fn physical_plan_config_no_projection_tab_cols_as_field() {
1907        let file_schema = aggr_test_schema();
1908
1909        // make a table_partition_col as a field
1910        let table_partition_col =
1911            Field::new("date", wrap_partition_type_in_dict(DataType::Utf8), true)
1912                .with_metadata(HashMap::from_iter(vec![(
1913                    "key_whatever".to_owned(),
1914                    "value_whatever".to_owned(),
1915                )]));
1916
1917        let conf = config_for_projection(
1918            Arc::clone(&file_schema),
1919            None,
1920            Statistics::new_unknown(&file_schema),
1921            vec![table_partition_col.clone()],
1922        );
1923
1924        // verify the proj_schema includes the last column and exactly the same the field it is defined
1925        let proj_schema = conf.projected_schema().unwrap();
1926        assert_eq!(proj_schema.fields().len(), file_schema.fields().len() + 1);
1927        assert_eq!(
1928            *proj_schema.field(file_schema.fields().len()),
1929            table_partition_col,
1930            "partition columns are the last columns and ust have all values defined in created field"
1931        );
1932    }
1933
1934    #[test]
1935    fn test_split_groups_by_statistics() -> Result<()> {
1936        use chrono::TimeZone;
1937        use datafusion_common::DFSchema;
1938        use datafusion_expr::execution_props::ExecutionProps;
1939        use datafusion_expr::physical_planning_context::PhysicalPlanningContext;
1940        use object_store::{ObjectMeta, path::Path};
1941
1942        struct File {
1943            name: &'static str,
1944            date: &'static str,
1945            statistics: Vec<Option<(Option<f64>, Option<f64>)>>,
1946        }
1947        impl File {
1948            fn new(
1949                name: &'static str,
1950                date: &'static str,
1951                statistics: Vec<Option<(f64, f64)>>,
1952            ) -> Self {
1953                Self::new_nullable(
1954                    name,
1955                    date,
1956                    statistics
1957                        .into_iter()
1958                        .map(|opt| opt.map(|(min, max)| (Some(min), Some(max))))
1959                        .collect(),
1960                )
1961            }
1962
1963            fn new_nullable(
1964                name: &'static str,
1965                date: &'static str,
1966                statistics: Vec<Option<(Option<f64>, Option<f64>)>>,
1967            ) -> Self {
1968                Self {
1969                    name,
1970                    date,
1971                    statistics,
1972                }
1973            }
1974        }
1975
1976        struct TestCase {
1977            name: &'static str,
1978            file_schema: Schema,
1979            files: Vec<File>,
1980            sort: Vec<SortExpr>,
1981            expected_result: Result<Vec<Vec<&'static str>>, &'static str>,
1982        }
1983
1984        use datafusion_expr::col;
1985        let cases = vec![
1986            TestCase {
1987                name: "test sort",
1988                file_schema: Schema::new(vec![Field::new(
1989                    "value".to_string(),
1990                    DataType::Float64,
1991                    false,
1992                )]),
1993                files: vec![
1994                    File::new("0", "2023-01-01", vec![Some((0.00, 0.49))]),
1995                    File::new("1", "2023-01-01", vec![Some((0.50, 1.00))]),
1996                    File::new("2", "2023-01-02", vec![Some((0.00, 1.00))]),
1997                ],
1998                sort: vec![col("value").sort(true, false)],
1999                expected_result: Ok(vec![vec!["0", "1"], vec!["2"]]),
2000            },
2001            // same input but file '2' is in the middle
2002            // test that we still order correctly
2003            TestCase {
2004                name: "test sort with files ordered differently",
2005                file_schema: Schema::new(vec![Field::new(
2006                    "value".to_string(),
2007                    DataType::Float64,
2008                    false,
2009                )]),
2010                files: vec![
2011                    File::new("0", "2023-01-01", vec![Some((0.00, 0.49))]),
2012                    File::new("2", "2023-01-02", vec![Some((0.00, 1.00))]),
2013                    File::new("1", "2023-01-01", vec![Some((0.50, 1.00))]),
2014                ],
2015                sort: vec![col("value").sort(true, false)],
2016                expected_result: Ok(vec![vec!["0", "1"], vec!["2"]]),
2017            },
2018            TestCase {
2019                name: "reverse sort",
2020                file_schema: Schema::new(vec![Field::new(
2021                    "value".to_string(),
2022                    DataType::Float64,
2023                    false,
2024                )]),
2025                files: vec![
2026                    File::new("0", "2023-01-01", vec![Some((0.00, 0.49))]),
2027                    File::new("1", "2023-01-01", vec![Some((0.50, 1.00))]),
2028                    File::new("2", "2023-01-02", vec![Some((0.00, 1.00))]),
2029                ],
2030                sort: vec![col("value").sort(false, true)],
2031                expected_result: Ok(vec![vec!["1", "0"], vec!["2"]]),
2032            },
2033            TestCase {
2034                name: "nullable sort columns, nulls last",
2035                file_schema: Schema::new(vec![Field::new(
2036                    "value".to_string(),
2037                    DataType::Float64,
2038                    true,
2039                )]),
2040                files: vec![
2041                    File::new_nullable(
2042                        "0",
2043                        "2023-01-01",
2044                        vec![Some((Some(0.00), Some(0.49)))],
2045                    ),
2046                    File::new_nullable("1", "2023-01-01", vec![Some((Some(0.50), None))]),
2047                    File::new_nullable("2", "2023-01-02", vec![Some((Some(0.00), None))]),
2048                ],
2049                sort: vec![col("value").sort(true, false)],
2050                expected_result: Ok(vec![vec!["0", "1"], vec!["2"]]),
2051            },
2052            TestCase {
2053                name: "nullable sort columns, nulls first",
2054                file_schema: Schema::new(vec![Field::new(
2055                    "value".to_string(),
2056                    DataType::Float64,
2057                    true,
2058                )]),
2059                files: vec![
2060                    File::new_nullable("0", "2023-01-01", vec![Some((None, Some(0.49)))]),
2061                    File::new_nullable(
2062                        "1",
2063                        "2023-01-01",
2064                        vec![Some((Some(0.50), Some(1.00)))],
2065                    ),
2066                    File::new_nullable("2", "2023-01-02", vec![Some((None, Some(1.00)))]),
2067                ],
2068                sort: vec![col("value").sort(true, true)],
2069                expected_result: Ok(vec![vec!["0", "1"], vec!["2"]]),
2070            },
2071            TestCase {
2072                name: "all three non-overlapping",
2073                file_schema: Schema::new(vec![Field::new(
2074                    "value".to_string(),
2075                    DataType::Float64,
2076                    false,
2077                )]),
2078                files: vec![
2079                    File::new("0", "2023-01-01", vec![Some((0.00, 0.49))]),
2080                    File::new("1", "2023-01-01", vec![Some((0.50, 0.99))]),
2081                    File::new("2", "2023-01-02", vec![Some((1.00, 1.49))]),
2082                ],
2083                sort: vec![col("value").sort(true, false)],
2084                expected_result: Ok(vec![vec!["0", "1", "2"]]),
2085            },
2086            TestCase {
2087                name: "all three overlapping",
2088                file_schema: Schema::new(vec![Field::new(
2089                    "value".to_string(),
2090                    DataType::Float64,
2091                    false,
2092                )]),
2093                files: vec![
2094                    File::new("0", "2023-01-01", vec![Some((0.00, 0.49))]),
2095                    File::new("1", "2023-01-01", vec![Some((0.00, 0.49))]),
2096                    File::new("2", "2023-01-02", vec![Some((0.00, 0.49))]),
2097                ],
2098                sort: vec![col("value").sort(true, false)],
2099                expected_result: Ok(vec![vec!["0"], vec!["1"], vec!["2"]]),
2100            },
2101            TestCase {
2102                name: "empty input",
2103                file_schema: Schema::new(vec![Field::new(
2104                    "value".to_string(),
2105                    DataType::Float64,
2106                    false,
2107                )]),
2108                files: vec![],
2109                sort: vec![col("value").sort(true, false)],
2110                expected_result: Ok(vec![]),
2111            },
2112            TestCase {
2113                name: "one file missing statistics",
2114                file_schema: Schema::new(vec![Field::new(
2115                    "value".to_string(),
2116                    DataType::Float64,
2117                    false,
2118                )]),
2119                files: vec![
2120                    File::new("0", "2023-01-01", vec![Some((0.00, 0.49))]),
2121                    File::new("1", "2023-01-01", vec![Some((0.00, 0.49))]),
2122                    File::new("2", "2023-01-02", vec![None]),
2123                ],
2124                sort: vec![col("value").sort(true, false)],
2125                expected_result: Err(
2126                    "construct min/max statistics for split_groups_by_statistics\ncaused by\ncollect min/max values\ncaused by\nget min/max for column: 'value'\ncaused by\nError during planning: statistics not found",
2127                ),
2128            },
2129        ];
2130
2131        for case in cases {
2132            let table_schema = Arc::new(Schema::new(
2133                case.file_schema
2134                    .fields()
2135                    .clone()
2136                    .into_iter()
2137                    .cloned()
2138                    .chain(Some(Arc::new(Field::new(
2139                        "date".to_string(),
2140                        DataType::Utf8,
2141                        false,
2142                    ))))
2143                    .collect::<Vec<_>>(),
2144            ));
2145            let Some(sort_order) = LexOrdering::new(
2146                case.sort
2147                    .into_iter()
2148                    .map(|expr| {
2149                        create_physical_sort_expr(
2150                            &expr,
2151                            &DFSchema::try_from(Arc::clone(&table_schema))?,
2152                            &ExecutionProps::default(),
2153                            &PhysicalPlanningContext::default(),
2154                        )
2155                    })
2156                    .collect::<Result<Vec<_>>>()?,
2157            ) else {
2158                return internal_err!("This test should always use an ordering");
2159            };
2160
2161            let partitioned_files = FileGroup::new(
2162                case.files.into_iter().map(From::from).collect::<Vec<_>>(),
2163            );
2164            let result = FileScanConfig::split_groups_by_statistics(
2165                &table_schema,
2166                std::slice::from_ref(&partitioned_files),
2167                &sort_order,
2168            );
2169            let results_by_name = result
2170                .as_ref()
2171                .map(|file_groups| {
2172                    file_groups
2173                        .iter()
2174                        .map(|file_group| {
2175                            file_group
2176                                .iter()
2177                                .map(|file| {
2178                                    partitioned_files
2179                                        .iter()
2180                                        .find_map(|f| {
2181                                            if f.object_meta == file.object_meta {
2182                                                Some(
2183                                                    f.object_meta
2184                                                        .location
2185                                                        .as_ref()
2186                                                        .rsplit('/')
2187                                                        .next()
2188                                                        .unwrap()
2189                                                        .trim_end_matches(".parquet"),
2190                                                )
2191                                            } else {
2192                                                None
2193                                            }
2194                                        })
2195                                        .unwrap()
2196                                })
2197                                .collect::<Vec<_>>()
2198                        })
2199                        .collect::<Vec<_>>()
2200                })
2201                .map_err(|e| e.strip_backtrace().leak() as &'static str);
2202
2203            assert_eq!(results_by_name, case.expected_result, "{}", case.name);
2204        }
2205
2206        return Ok(());
2207
2208        impl From<File> for PartitionedFile {
2209            fn from(file: File) -> Self {
2210                let object_meta = ObjectMeta {
2211                    location: Path::from(format!(
2212                        "data/date={}/{}.parquet",
2213                        file.date, file.name
2214                    )),
2215                    last_modified: chrono::Utc.timestamp_nanos(0),
2216                    size: 0,
2217                    e_tag: None,
2218                    version: None,
2219                };
2220                let statistics = Arc::new(Statistics {
2221                    num_rows: Precision::Absent,
2222                    total_byte_size: Precision::Absent,
2223                    column_statistics: file
2224                        .statistics
2225                        .into_iter()
2226                        .map(|stats| {
2227                            stats
2228                                .map(|(min, max)| ColumnStatistics {
2229                                    null_count: Precision::Exact(usize::from(
2230                                        min.is_none() || max.is_none(),
2231                                    )),
2232                                    min_value: Precision::Exact(ScalarValue::Float64(
2233                                        min,
2234                                    )),
2235                                    max_value: Precision::Exact(ScalarValue::Float64(
2236                                        max,
2237                                    )),
2238                                    ..Default::default()
2239                                })
2240                                .unwrap_or_default()
2241                        })
2242                        .collect::<Vec<_>>(),
2243                });
2244                PartitionedFile::new_from_meta(object_meta)
2245                    .with_partition_values(vec![ScalarValue::from(file.date)])
2246                    .with_statistics(statistics)
2247            }
2248        }
2249    }
2250
2251    // sets default for configs that play no role in projections
2252    fn config_with_constraints(
2253        table_schema: TableSchema,
2254        statistics: Statistics,
2255        constraints: Vec<Constraint>,
2256        projection: Option<Vec<usize>>,
2257    ) -> FileScanConfig {
2258        FileScanConfigBuilder::new(
2259            ObjectStoreUrl::parse("test:///").unwrap(),
2260            Arc::new(MockSource::new(table_schema)),
2261        )
2262        .with_statistics(statistics)
2263        .with_constraints(Constraints::new_unverified(constraints))
2264        .with_projection_indices(projection)
2265        .unwrap()
2266        .build()
2267    }
2268
2269    /// A key column has one distinct value per row, which no file format records.
2270    #[test]
2271    fn key_columns_report_a_distinct_count() {
2272        let file_schema = Arc::new(Schema::new(vec![
2273            Field::new("id", DataType::Int32, false),
2274            Field::new("part", DataType::Int32, false),
2275            Field::new("code", DataType::Int32, true),
2276        ]));
2277        let table_schema = TableSchema::builder(Arc::clone(&file_schema)).build();
2278        let mut statistics = Statistics::new_unknown(&file_schema);
2279        statistics.num_rows = Precision::Exact(100);
2280        // A unique column may repeat NULL, which is not a distinct value.
2281        statistics.column_statistics[2].null_count = Precision::Exact(10);
2282
2283        let stats = |constraints| {
2284            config_with_constraints(
2285                table_schema.clone(),
2286                statistics.clone(),
2287                constraints,
2288                None,
2289            )
2290            .statistics()
2291        };
2292
2293        // A primary key cannot be null, so the count is as exact as the row count.
2294        let primary_key = stats(vec![Constraint::PrimaryKey(vec![0])]);
2295        assert_eq!(
2296            primary_key.column_statistics[0].distinct_count,
2297            Precision::Exact(100)
2298        );
2299        assert_eq!(
2300            primary_key.column_statistics[1].distinct_count,
2301            Precision::Absent
2302        );
2303
2304        // The nulls a unique column may repeat are known here, so this is exact too.
2305        let unique = stats(vec![Constraint::Unique(vec![2])]);
2306        assert_eq!(
2307            unique.column_statistics[2].distinct_count,
2308            Precision::Exact(90)
2309        );
2310
2311        // With an unknown null count it is not exact.
2312        let mut unknown_nulls = statistics.clone();
2313        unknown_nulls.column_statistics[2].null_count = Precision::Absent;
2314        let unique = config_with_constraints(
2315            table_schema.clone(),
2316            unknown_nulls,
2317            vec![Constraint::Unique(vec![2])],
2318            None,
2319        )
2320        .statistics();
2321        assert_eq!(
2322            unique.column_statistics[2].distinct_count,
2323            Precision::Inexact(100)
2324        );
2325
2326        // A composite key leaves its columns alone: only the combination is unique.
2327        let composite = stats(vec![Constraint::PrimaryKey(vec![0, 1])]);
2328        assert_eq!(
2329            composite.column_statistics[0].distinct_count,
2330            Precision::Absent
2331        );
2332        assert_eq!(
2333            composite.column_statistics[1].distinct_count,
2334            Precision::Absent
2335        );
2336    }
2337
2338    /// The count has to reach the plan, which reads statistics through the projection.
2339    #[test]
2340    fn a_projected_scan_keeps_the_key_distinct_count() {
2341        let file_schema = Arc::new(Schema::new(vec![
2342            Field::new("value", DataType::Int32, true),
2343            Field::new("id", DataType::Int32, false),
2344        ]));
2345        let table_schema = TableSchema::builder(Arc::clone(&file_schema)).build();
2346        let mut statistics = Statistics::new_unknown(&file_schema);
2347        statistics.num_rows = Precision::Exact(100);
2348
2349        let config = config_with_constraints(
2350            table_schema,
2351            statistics,
2352            vec![Constraint::PrimaryKey(vec![1])],
2353            Some(vec![1]),
2354        );
2355
2356        let projected = config.partition_statistics(None).unwrap();
2357        assert_eq!(
2358            projected.column_statistics[0].distinct_count,
2359            Precision::Exact(100)
2360        );
2361    }
2362
2363    fn config_for_projection(
2364        file_schema: SchemaRef,
2365        projection: Option<Vec<usize>>,
2366        statistics: Statistics,
2367        table_partition_cols: Vec<Field>,
2368    ) -> FileScanConfig {
2369        let table_schema = TableSchema::builder(file_schema)
2370            .with_table_partition_cols(
2371                table_partition_cols
2372                    .into_iter()
2373                    .map(Arc::new)
2374                    .collect::<Fields>(),
2375            )
2376            .build();
2377        FileScanConfigBuilder::new(
2378            ObjectStoreUrl::parse("test:///").unwrap(),
2379            Arc::new(MockSource::new(table_schema.clone())),
2380        )
2381        .with_projection_indices(projection)
2382        .unwrap()
2383        .with_statistics(statistics)
2384        .build()
2385    }
2386
2387    #[test]
2388    fn test_file_scan_config_builder() {
2389        let file_schema = aggr_test_schema();
2390        let object_store_url = ObjectStoreUrl::parse("test:///").unwrap();
2391
2392        let table_schema = TableSchemaBuilder::from(&file_schema)
2393            .with_table_partition_cols(vec![Arc::new(Field::new(
2394                "date",
2395                wrap_partition_type_in_dict(DataType::Utf8),
2396                false,
2397            ))])
2398            .build();
2399
2400        let file_source: Arc<dyn FileSource> =
2401            Arc::new(MockSource::new(table_schema.clone()));
2402
2403        // Create a builder with required parameters
2404        let builder = FileScanConfigBuilder::new(
2405            object_store_url.clone(),
2406            Arc::clone(&file_source),
2407        );
2408
2409        // Build with various configurations
2410        let config = builder
2411            .with_limit(Some(1000))
2412            .with_projection_indices(Some(vec![0, 1]))
2413            .unwrap()
2414            .with_statistics(Statistics::new_unknown(&file_schema))
2415            .with_file_groups(vec![FileGroup::new(vec![PartitionedFile::new(
2416                "test.parquet".to_string(),
2417                1024,
2418            )])])
2419            .with_output_ordering(vec![
2420                [PhysicalSortExpr::new_default(Arc::new(Column::new(
2421                    "date", 0,
2422                )))]
2423                .into(),
2424            ])
2425            .with_file_compression_type(FileCompressionType::UNCOMPRESSED)
2426            .build();
2427
2428        // Verify the built config has all the expected values
2429        assert_eq!(config.object_store_url, object_store_url);
2430        assert_eq!(*config.file_schema(), file_schema);
2431        assert_eq!(config.limit, Some(1000));
2432        assert_eq!(
2433            config
2434                .file_source
2435                .projection()
2436                .as_ref()
2437                .map(|p| p.column_indices()),
2438            Some(vec![0, 1])
2439        );
2440        assert_eq!(config.table_partition_cols().len(), 1);
2441        assert_eq!(config.table_partition_cols()[0].name(), "date");
2442        assert_eq!(config.file_groups.len(), 1);
2443        assert_eq!(config.file_groups[0].len(), 1);
2444        assert_eq!(
2445            config.file_groups[0][0].object_meta.location.as_ref(),
2446            "test.parquet"
2447        );
2448        assert_eq!(
2449            config.file_compression_type,
2450            FileCompressionType::UNCOMPRESSED
2451        );
2452        assert_eq!(config.output_ordering.len(), 1);
2453    }
2454
2455    #[test]
2456    fn equivalence_properties_after_schema_change() {
2457        let file_schema = aggr_test_schema();
2458        let object_store_url = ObjectStoreUrl::parse("test:///").unwrap();
2459
2460        let table_schema = TableSchema::from(&file_schema);
2461
2462        // Create a file source with a filter
2463        let file_source: Arc<dyn FileSource> = Arc::new(
2464            MockSource::new(table_schema.clone()).with_filter(Arc::new(BinaryExpr::new(
2465                col("c2", &file_schema).unwrap(),
2466                Operator::Eq,
2467                Arc::new(Literal::new(ScalarValue::Int32(Some(10)))),
2468            ))),
2469        );
2470
2471        let config = FileScanConfigBuilder::new(
2472            object_store_url.clone(),
2473            Arc::clone(&file_source),
2474        )
2475        .with_projection_indices(Some(vec![0, 1, 2]))
2476        .unwrap()
2477        .build();
2478
2479        // Simulate projection being updated. Since the filter has already been pushed down,
2480        // the new projection won't include the filtered column.
2481        let exprs = ProjectionExprs::new(vec![ProjectionExpr::new(
2482            col("c1", &file_schema).unwrap(),
2483            "c1",
2484        )]);
2485        let data_source = config
2486            .try_swapping_with_projection(&exprs)
2487            .unwrap()
2488            .unwrap();
2489
2490        // Gather the equivalence properties from the new data source. There should
2491        // be no equivalence class for column c2 since it was removed by the projection.
2492        let eq_properties = data_source.eq_properties();
2493        let eq_group = eq_properties.eq_group();
2494
2495        for class in eq_group.iter() {
2496            for expr in class.iter() {
2497                if let Some(col) = expr.downcast_ref::<Column>() {
2498                    assert_ne!(
2499                        col.name(),
2500                        "c2",
2501                        "c2 should not be present in any equivalence class"
2502                    );
2503                }
2504            }
2505        }
2506    }
2507
2508    #[test]
2509    fn test_file_scan_config_builder_defaults() {
2510        let file_schema = aggr_test_schema();
2511        let object_store_url = ObjectStoreUrl::parse("test:///").unwrap();
2512
2513        let table_schema = TableSchema::from(&file_schema);
2514
2515        let file_source: Arc<dyn FileSource> =
2516            Arc::new(MockSource::new(table_schema.clone()));
2517
2518        // Create a builder with only required parameters and build without any additional configurations
2519        let config = FileScanConfigBuilder::new(
2520            object_store_url.clone(),
2521            Arc::clone(&file_source),
2522        )
2523        .build();
2524
2525        // Verify default values
2526        assert_eq!(config.object_store_url, object_store_url);
2527        assert_eq!(*config.file_schema(), file_schema);
2528        assert_eq!(config.limit, None);
2529        // When no projection is specified, the file source should have an unprojected projection
2530        // (i.e., all columns)
2531        let expected_projection: Vec<usize> = (0..file_schema.fields().len()).collect();
2532        assert_eq!(
2533            config
2534                .file_source
2535                .projection()
2536                .as_ref()
2537                .map(|p| p.column_indices()),
2538            Some(expected_projection)
2539        );
2540        assert!(config.table_partition_cols().is_empty());
2541        assert!(config.file_groups.is_empty());
2542        assert_eq!(
2543            config.file_compression_type,
2544            FileCompressionType::UNCOMPRESSED
2545        );
2546        assert!(config.output_ordering.is_empty());
2547        assert!(config.constraints.is_empty());
2548
2549        // Verify statistics are set to unknown
2550        assert_eq!(config.statistics().num_rows, Precision::Absent);
2551        assert_eq!(config.statistics().total_byte_size, Precision::Absent);
2552        assert_eq!(
2553            config.statistics().column_statistics.len(),
2554            file_schema.fields().len()
2555        );
2556        for stat in config.statistics().column_statistics {
2557            assert_eq!(stat.distinct_count, Precision::Absent);
2558            assert_eq!(stat.min_value, Precision::Absent);
2559            assert_eq!(stat.max_value, Precision::Absent);
2560            assert_eq!(stat.null_count, Precision::Absent);
2561        }
2562    }
2563
2564    #[test]
2565    fn test_file_scan_config_builder_new_from() {
2566        let schema = aggr_test_schema();
2567        let object_store_url = ObjectStoreUrl::parse("test:///").unwrap();
2568        let partition_cols = vec![Field::new(
2569            "date",
2570            wrap_partition_type_in_dict(DataType::Utf8),
2571            false,
2572        )];
2573        let file = PartitionedFile::new("test_file.parquet", 100);
2574
2575        let table_schema = TableSchemaBuilder::from(&schema)
2576            .with_table_partition_cols(
2577                partition_cols
2578                    .iter()
2579                    .map(|f| Arc::new(f.clone()))
2580                    .collect::<Fields>(),
2581            )
2582            .build();
2583
2584        let file_source: Arc<dyn FileSource> =
2585            Arc::new(MockSource::new(table_schema.clone()));
2586
2587        // Create a config with non-default values
2588        let original_config = FileScanConfigBuilder::new(
2589            object_store_url.clone(),
2590            Arc::clone(&file_source),
2591        )
2592        .with_projection_indices(Some(vec![0, 2]))
2593        .unwrap()
2594        .with_limit(Some(10))
2595        .with_file(file.clone())
2596        .with_constraints(Constraints::default())
2597        .build();
2598
2599        // Create a new builder from the config
2600        let new_builder = FileScanConfigBuilder::from(original_config);
2601
2602        // Build a new config from this builder
2603        let new_config = new_builder.build();
2604
2605        // Verify properties match
2606        let partition_cols = partition_cols.into_iter().map(Arc::new).collect::<Vec<_>>();
2607        assert_eq!(new_config.object_store_url, object_store_url);
2608        assert_eq!(*new_config.file_schema(), schema);
2609        assert_eq!(
2610            new_config
2611                .file_source
2612                .projection()
2613                .as_ref()
2614                .map(|p| p.column_indices()),
2615            Some(vec![0, 2])
2616        );
2617        assert_eq!(new_config.limit, Some(10));
2618        assert_eq!(
2619            *new_config.table_partition_cols(),
2620            Fields::from(partition_cols)
2621        );
2622        assert_eq!(new_config.file_groups.len(), 1);
2623        assert_eq!(new_config.file_groups[0].len(), 1);
2624        assert_eq!(
2625            new_config.file_groups[0][0].object_meta.location.as_ref(),
2626            "test_file.parquet"
2627        );
2628        assert_eq!(new_config.constraints, Constraints::default());
2629    }
2630
2631    #[test]
2632    fn test_split_groups_by_statistics_with_target_partitions() -> Result<()> {
2633        use datafusion_common::DFSchema;
2634        use datafusion_expr::{
2635            col, execution_props::ExecutionProps,
2636            physical_planning_context::PhysicalPlanningContext,
2637        };
2638
2639        let schema = Arc::new(Schema::new(vec![Field::new(
2640            "value",
2641            DataType::Float64,
2642            false,
2643        )]));
2644
2645        // Setup sort expression
2646        let exec_props = ExecutionProps::new();
2647        let df_schema = DFSchema::try_from_qualified_schema("test", schema.as_ref())?;
2648        let sort_expr = [col("value").sort(true, false)];
2649        let sort_ordering = sort_expr
2650            .map(|expr| {
2651                create_physical_sort_expr(
2652                    &expr,
2653                    &df_schema,
2654                    &exec_props,
2655                    &PhysicalPlanningContext::default(),
2656                )
2657                .unwrap()
2658            })
2659            .into();
2660
2661        // Test case parameters
2662        struct TestCase {
2663            name: String,
2664            file_count: usize,
2665            overlap_factor: f64,
2666            target_partitions: usize,
2667            expected_partition_count: usize,
2668        }
2669
2670        let test_cases = vec![
2671            // Basic cases
2672            TestCase {
2673                name: "no_overlap_10_files_4_partitions".to_string(),
2674                file_count: 10,
2675                overlap_factor: 0.0,
2676                target_partitions: 4,
2677                expected_partition_count: 4,
2678            },
2679            TestCase {
2680                name: "medium_overlap_20_files_5_partitions".to_string(),
2681                file_count: 20,
2682                overlap_factor: 0.5,
2683                target_partitions: 5,
2684                expected_partition_count: 5,
2685            },
2686            TestCase {
2687                name: "high_overlap_30_files_3_partitions".to_string(),
2688                file_count: 30,
2689                overlap_factor: 0.8,
2690                target_partitions: 3,
2691                expected_partition_count: 7,
2692            },
2693            // Edge cases
2694            TestCase {
2695                name: "fewer_files_than_partitions".to_string(),
2696                file_count: 3,
2697                overlap_factor: 0.0,
2698                target_partitions: 10,
2699                expected_partition_count: 3, // Should only create as many partitions as files
2700            },
2701            TestCase {
2702                name: "single_file".to_string(),
2703                file_count: 1,
2704                overlap_factor: 0.0,
2705                target_partitions: 5,
2706                expected_partition_count: 1, // Should create only one partition
2707            },
2708            TestCase {
2709                name: "empty_files".to_string(),
2710                file_count: 0,
2711                overlap_factor: 0.0,
2712                target_partitions: 3,
2713                expected_partition_count: 0, // Empty result for empty input
2714            },
2715        ];
2716
2717        for case in test_cases {
2718            println!("Running test case: {}", case.name);
2719
2720            // Generate files using bench utility function
2721            let file_groups = generate_test_files(case.file_count, case.overlap_factor);
2722
2723            // Call the function under test
2724            let result =
2725                FileScanConfig::split_groups_by_statistics_with_target_partitions(
2726                    &schema,
2727                    &file_groups,
2728                    &sort_ordering,
2729                    case.target_partitions,
2730                )?;
2731
2732            // Verify results
2733            println!(
2734                "Created {} partitions (target was {})",
2735                result.len(),
2736                case.target_partitions
2737            );
2738
2739            // Check partition count
2740            assert_eq!(
2741                result.len(),
2742                case.expected_partition_count,
2743                "Case '{}': Unexpected partition count",
2744                case.name
2745            );
2746
2747            // Verify sort integrity
2748            assert!(
2749                verify_sort_integrity(&result),
2750                "Case '{}': Files within partitions are not properly ordered",
2751                case.name
2752            );
2753
2754            // Distribution check for partitions
2755            if case.file_count > 1 && case.expected_partition_count > 1 {
2756                let group_sizes: Vec<usize> = result.iter().map(FileGroup::len).collect();
2757                let max_size = *group_sizes.iter().max().unwrap();
2758                let min_size = *group_sizes.iter().min().unwrap();
2759
2760                // Check partition balancing - difference shouldn't be extreme
2761                let avg_files_per_partition =
2762                    case.file_count as f64 / case.expected_partition_count as f64;
2763                assert!(
2764                    (max_size as f64) < 2.0 * avg_files_per_partition,
2765                    "Case '{}': Unbalanced distribution. Max partition size {} exceeds twice the average {}",
2766                    case.name,
2767                    max_size,
2768                    avg_files_per_partition
2769                );
2770
2771                println!("Distribution - min files: {min_size}, max files: {max_size}");
2772            }
2773        }
2774
2775        // Test error case: zero target partitions
2776        let empty_groups: Vec<FileGroup> = vec![];
2777        let err = FileScanConfig::split_groups_by_statistics_with_target_partitions(
2778            &schema,
2779            &empty_groups,
2780            &sort_ordering,
2781            0,
2782        )
2783        .unwrap_err();
2784
2785        assert!(
2786            err.to_string()
2787                .contains("target_partitions must be greater than 0"),
2788            "Expected error for zero target partitions"
2789        );
2790
2791        Ok(())
2792    }
2793
2794    #[test]
2795    fn split_groups_by_statistics_preserves_exact_empty_files() -> Result<()> {
2796        let schema = Arc::new(Schema::new(vec![Field::new(
2797            "value",
2798            DataType::Float64,
2799            false,
2800        )]));
2801        let sort_order = LexOrdering::new(vec![PhysicalSortExpr::new_default(Arc::new(
2802            Column::new("value", 0),
2803        ))])
2804        .unwrap();
2805
2806        let mixed_files = vec![FileGroup::new(vec![
2807            make_file_with_stats("high", 20.0, 29.0),
2808            make_exact_empty_file("empty"),
2809            make_file_with_stats("low", 0.0, 9.0),
2810        ])];
2811        let split = FileScanConfig::split_groups_by_statistics(
2812            &schema,
2813            &mixed_files,
2814            &sort_order,
2815        )?;
2816        let split_with_target =
2817            FileScanConfig::split_groups_by_statistics_with_target_partitions(
2818                &schema,
2819                &mixed_files,
2820                &sort_order,
2821                2,
2822            )?;
2823
2824        for result in [split, split_with_target] {
2825            assert!(verify_sort_integrity(&result));
2826            let mut file_names = result
2827                .iter()
2828                .flat_map(FileGroup::iter)
2829                .map(|file| file.object_meta.location.to_string())
2830                .collect::<Vec<_>>();
2831            file_names.sort();
2832            assert_eq!(file_names, ["empty", "high", "low"]);
2833            assert!(result.iter().all(|group| !group.is_empty()));
2834        }
2835
2836        let empty_files = vec![FileGroup::new(vec![
2837            make_exact_empty_file("empty1"),
2838            make_exact_empty_file("empty2"),
2839        ])];
2840        let split = FileScanConfig::split_groups_by_statistics(
2841            &schema,
2842            &empty_files,
2843            &sort_order,
2844        )?;
2845        let split_with_target =
2846            FileScanConfig::split_groups_by_statistics_with_target_partitions(
2847                &schema,
2848                &empty_files,
2849                &sort_order,
2850                2,
2851            )?;
2852
2853        for result in [split, split_with_target] {
2854            assert!(verify_sort_integrity(&result));
2855            assert_eq!(result.len(), 1);
2856            let file_names = result[0]
2857                .iter()
2858                .map(|file| file.object_meta.location.to_string())
2859                .collect::<Vec<_>>();
2860            assert_eq!(file_names, ["empty1", "empty2"]);
2861        }
2862
2863        Ok(())
2864    }
2865
2866    #[test]
2867    fn test_partition_statistics_projection() {
2868        // This test verifies that partition_statistics applies projection correctly.
2869        // The old implementation had a bug where it returned file group statistics
2870        // without applying the projection, returning all column statistics instead
2871        // of just the projected ones.
2872
2873        use crate::source::DataSourceExec;
2874        use datafusion_physical_plan::statistics::{StatisticsArgs, StatisticsContext};
2875
2876        let schema = Arc::new(Schema::new(vec![
2877            Field::new("col0", DataType::Int32, false),
2878            Field::new("col1", DataType::Int32, false),
2879            Field::new("col2", DataType::Int32, false),
2880            Field::new("col3", DataType::Int32, false),
2881        ]));
2882
2883        // Create statistics for all 4 columns
2884        let file_group_stats = Statistics {
2885            num_rows: Precision::Exact(100),
2886            total_byte_size: Precision::Exact(1024),
2887            column_statistics: vec![
2888                ColumnStatistics {
2889                    null_count: Precision::Exact(0),
2890                    ..ColumnStatistics::new_unknown()
2891                },
2892                ColumnStatistics {
2893                    null_count: Precision::Exact(5),
2894                    ..ColumnStatistics::new_unknown()
2895                },
2896                ColumnStatistics {
2897                    null_count: Precision::Exact(10),
2898                    ..ColumnStatistics::new_unknown()
2899                },
2900                ColumnStatistics {
2901                    null_count: Precision::Exact(15),
2902                    ..ColumnStatistics::new_unknown()
2903                },
2904            ],
2905        };
2906
2907        // Create a file group with statistics
2908        let file_group = FileGroup::new(vec![PartitionedFile::new("test.parquet", 1024)])
2909            .with_statistics(Arc::new(file_group_stats));
2910
2911        let table_schema = TableSchema::from(&schema);
2912
2913        // Create a FileScanConfig with projection: only keep columns 0 and 2
2914        let config = FileScanConfigBuilder::new(
2915            ObjectStoreUrl::parse("test:///").unwrap(),
2916            Arc::new(MockSource::new(table_schema.clone())),
2917        )
2918        .with_projection_indices(Some(vec![0, 2]))
2919        .unwrap() // Only project columns 0 and 2
2920        .with_file_groups(vec![file_group])
2921        .build();
2922
2923        // Create a DataSourceExec from the config
2924        let exec = DataSourceExec::from_data_source(config);
2925
2926        // Get statistics for partition 0
2927        let partition_stats = StatisticsContext::new()
2928            .compute(
2929                exec.as_ref(),
2930                &StatisticsArgs::new().with_partition(Some(0)),
2931            )
2932            .unwrap();
2933
2934        // Verify that only 2 columns are in the statistics (the projected ones)
2935        assert_eq!(
2936            partition_stats.column_statistics.len(),
2937            2,
2938            "Expected 2 column statistics (projected), but got {}",
2939            partition_stats.column_statistics.len()
2940        );
2941
2942        // Verify the column statistics are for columns 0 and 2
2943        assert_eq!(
2944            partition_stats.column_statistics[0].null_count,
2945            Precision::Exact(0),
2946            "First projected column should be col0 with 0 nulls"
2947        );
2948        assert_eq!(
2949            partition_stats.column_statistics[1].null_count,
2950            Precision::Exact(10),
2951            "Second projected column should be col2 with 10 nulls"
2952        );
2953
2954        // Verify row count and byte size
2955        assert_eq!(partition_stats.num_rows, Precision::Exact(100));
2956        assert_eq!(partition_stats.total_byte_size, Precision::Exact(800));
2957    }
2958
2959    #[test]
2960    fn test_statistics_with_filter() {
2961        assert_num_rows_with_filter(Precision::Absent, Precision::Absent);
2962        assert_num_rows_with_filter(Precision::Exact(100), Precision::Inexact(100));
2963        assert_num_rows_with_filter(Precision::Inexact(100), Precision::Inexact(100));
2964        assert_num_rows_with_filter(Precision::Exact(0), Precision::Exact(0));
2965
2966        /// Creates a [`FileScanConfig`] with a filter and calls [`FileScanConfig::statistics`].
2967        /// Then the function checks the output num_rows stats, given the input num_rows stats.
2968        fn assert_num_rows_with_filter(
2969            input_num_rows: Precision<usize>,
2970            expected_num_rows: Precision<usize>,
2971        ) {
2972            let schema = Arc::new(Schema::new(vec![Field::new(
2973                "col0",
2974                DataType::Int32,
2975                false,
2976            )]));
2977
2978            let stats =
2979                Statistics::new_unknown(schema.as_ref()).with_num_rows(input_num_rows);
2980            let file_group =
2981                FileGroup::new(vec![PartitionedFile::new("test.parquet", 1024)]);
2982
2983            let table_schema = TableSchema::from(&schema);
2984            let config = FileScanConfigBuilder::new(
2985                ObjectStoreUrl::parse("test:///").unwrap(),
2986                Arc::new(MockSource::new(table_schema.clone()).with_filter(Arc::new(
2987                    Literal::new(ScalarValue::Boolean(Some(true))),
2988                ))),
2989            )
2990            .with_file_groups(vec![file_group])
2991            .with_statistics(stats)
2992            .build();
2993
2994            assert_eq!(config.statistics().num_rows, expected_num_rows,);
2995        }
2996    }
2997
2998    /// Regression test for reusing a `DataSourceExec` after its execution-local
2999    /// shared work queue has been drained.
3000    ///
3001    /// This test uses a single file group with two files so the scan creates a
3002    /// shared unopened-file queue. Executing after `reset_state` must recreate
3003    /// the shared queue and return the same rows again.
3004    #[tokio::test]
3005    async fn reset_state_recreates_shared_work_source() -> Result<()> {
3006        let schema = Arc::new(Schema::new(vec![Field::new(
3007            "value",
3008            DataType::Int32,
3009            false,
3010        )]));
3011        let file_source = Arc::new(
3012            MockSource::new(Arc::clone(&schema))
3013                .with_file_opener(Arc::new(ResetStateTestFileOpener { schema })),
3014        );
3015
3016        let config =
3017            FileScanConfigBuilder::new(ObjectStoreUrl::local_filesystem(), file_source)
3018                .with_file_group(FileGroup::new(vec![
3019                    PartitionedFile::new("file1.parquet", 100),
3020                    PartitionedFile::new("file2.parquet", 100),
3021                ]))
3022                .build();
3023
3024        let exec: Arc<dyn ExecutionPlan> = DataSourceExec::from_data_source(config);
3025        let task_ctx = Arc::new(TaskContext::default());
3026
3027        // Running the same scan after resetting the state, should
3028        // produce the same answer.
3029        let first_run = collect(Arc::clone(&exec), Arc::clone(&task_ctx)).await?;
3030        let reset_exec = exec.reset_state()?;
3031        let second_run = collect(reset_exec, task_ctx).await?;
3032
3033        let expected = [
3034            "+-------+",
3035            "| value |",
3036            "+-------+",
3037            "| 1     |",
3038            "| 2     |",
3039            "+-------+",
3040        ];
3041        assert_batches_eq!(expected, &first_run);
3042        assert_batches_eq!(expected, &second_run);
3043
3044        Ok(())
3045    }
3046
3047    /// Test-only `FileOpener` that turns file names like `file1.parquet` into a
3048    /// single-batch stream containing that numeric value
3049    #[derive(Debug)]
3050    struct ResetStateTestFileOpener {
3051        schema: SchemaRef,
3052    }
3053
3054    impl crate::file_stream::FileOpener for ResetStateTestFileOpener {
3055        fn open(
3056            &self,
3057            file: PartitionedFile,
3058        ) -> Result<crate::file_stream::FileOpenFuture> {
3059            let value = file
3060                .object_meta
3061                .location
3062                .as_ref()
3063                .trim_start_matches("file")
3064                .trim_end_matches(".parquet")
3065                .parse::<i32>()
3066                .expect("invalid test file name");
3067            let schema = Arc::clone(&self.schema);
3068            Ok(async move {
3069                let batch = RecordBatch::try_new(
3070                    schema,
3071                    vec![Arc::new(Int32Array::from(vec![value]))],
3072                )
3073                .expect("test batch should be valid");
3074                Ok(stream::iter(vec![Ok(batch)]).boxed())
3075            }
3076            .boxed())
3077        }
3078    }
3079
3080    /// A scan that advertises an output ordering never shares files between
3081    /// partitions, even if `preserve_order` is cleared after it is built.
3082    #[test]
3083    fn output_ordering_keeps_files_in_order() {
3084        let schema =
3085            Arc::new(Schema::new(vec![Field::new("a", DataType::Float64, false)]));
3086        let sort_expr = PhysicalSortExpr::new_default(Arc::new(Column::new("a", 0)));
3087        let mut config = FileScanConfigBuilder::new(
3088            ObjectStoreUrl::local_filesystem(),
3089            Arc::new(MockSource::new(schema)),
3090        )
3091        .with_file_groups(vec![
3092            FileGroup::new(vec![make_file_with_stats("file1", 0.0, 9.0)]),
3093            FileGroup::new(vec![make_file_with_stats("file2", 10.0, 19.0)]),
3094        ])
3095        .with_output_ordering(vec![LexOrdering::new(vec![sort_expr]).unwrap()])
3096        .build();
3097        let options = ConfigOptions::default();
3098
3099        config.preserve_order = false;
3100        assert!(config.preserves_file_order());
3101        assert!(config.create_sibling_state(&options).is_none());
3102
3103        config.output_ordering = vec![];
3104        assert!(!config.preserves_file_order());
3105        assert!(config.create_sibling_state(&options).is_some());
3106
3107        // An explicit `preserve_order` keeps file order without an output ordering
3108        config.preserve_order = true;
3109        assert!(config.preserves_file_order());
3110        assert!(config.create_sibling_state(&options).is_none());
3111    }
3112
3113    #[test]
3114    fn test_output_partitioning_not_partitioned_by_file_group() {
3115        let file_schema = aggr_test_schema();
3116        let partition_col =
3117            Field::new("date", wrap_partition_type_in_dict(DataType::Utf8), false);
3118
3119        let config = config_for_projection(
3120            Arc::clone(&file_schema),
3121            None,
3122            Statistics::new_unknown(&file_schema),
3123            vec![partition_col],
3124        );
3125
3126        // output_partitioning defaults to None
3127        let partitioning = config.output_partitioning();
3128        assert!(matches!(partitioning, Partitioning::UnknownPartitioning(_)));
3129    }
3130
3131    #[test]
3132    fn test_declared_output_partitioning_projects_with_scan() {
3133        let file_schema = aggr_test_schema();
3134        let output_partitioning =
3135            Partitioning::Hash(vec![Arc::new(Column::new("c2", 1))], 4);
3136
3137        let mut config = config_for_projection(
3138            Arc::clone(&file_schema),
3139            Some(vec![1, 2]),
3140            Statistics::new_unknown(&file_schema),
3141            vec![],
3142        );
3143        config.file_groups = vec![
3144            FileGroup::new(vec![PartitionedFile::new("f1.parquet".to_string(), 1024)]),
3145            FileGroup::new(vec![PartitionedFile::new("f2.parquet".to_string(), 1024)]),
3146            FileGroup::new(vec![PartitionedFile::new("f3.parquet".to_string(), 1024)]),
3147            FileGroup::new(vec![PartitionedFile::new("f4.parquet".to_string(), 1024)]),
3148        ];
3149        config.output_partitioning = Some(output_partitioning);
3150
3151        match config.output_partitioning() {
3152            Partitioning::Hash(exprs, num_partitions) => {
3153                assert_eq!(num_partitions, 4);
3154                assert_eq!(exprs.len(), 1);
3155                let column = exprs[0].downcast_ref::<Column>().unwrap();
3156                assert_eq!(column.name(), "c2");
3157                assert_eq!(column.index(), 0);
3158            }
3159            _ => panic!("Expected Hash partitioning"),
3160        }
3161
3162        let mut config = config_for_projection(
3163            Arc::clone(&file_schema),
3164            Some(vec![2]),
3165            Statistics::new_unknown(&file_schema),
3166            vec![],
3167        );
3168        config.file_groups = vec![
3169            FileGroup::new(vec![PartitionedFile::new("f1.parquet".to_string(), 1024)]),
3170            FileGroup::new(vec![PartitionedFile::new("f2.parquet".to_string(), 1024)]),
3171            FileGroup::new(vec![PartitionedFile::new("f3.parquet".to_string(), 1024)]),
3172            FileGroup::new(vec![PartitionedFile::new("f4.parquet".to_string(), 1024)]),
3173        ];
3174        config.output_partitioning =
3175            Some(Partitioning::Hash(vec![Arc::new(Column::new("c2", 1))], 4));
3176
3177        assert!(matches!(
3178            config.output_partitioning(),
3179            Partitioning::UnknownPartitioning(4)
3180        ));
3181    }
3182
3183    #[test]
3184    fn test_output_partitioning_no_partition_columns() {
3185        let file_schema = aggr_test_schema();
3186        let config = config_for_projection(
3187            Arc::clone(&file_schema),
3188            None,
3189            Statistics::new_unknown(&file_schema),
3190            vec![], // No partition columns
3191        );
3192
3193        let partitioning = config.output_partitioning();
3194        assert!(matches!(partitioning, Partitioning::UnknownPartitioning(_)));
3195
3196        let partitioning = output_range_partitioning_from_split_points(
3197            config.file_source.table_schema().table_schema(),
3198            config.table_partition_cols(),
3199            vec![],
3200        )
3201        .unwrap();
3202        assert!(partitioning.is_none());
3203    }
3204
3205    #[test]
3206    fn test_output_partitioning_with_partition_columns() {
3207        let file_schema = aggr_test_schema();
3208
3209        // Test single partition column
3210        let single_partition_col = vec![Field::new(
3211            "date",
3212            wrap_partition_type_in_dict(DataType::Utf8),
3213            false,
3214        )];
3215
3216        let mut config = config_for_projection(
3217            Arc::clone(&file_schema),
3218            None,
3219            Statistics::new_unknown(&file_schema),
3220            single_partition_col,
3221        );
3222        config.file_groups = vec![
3223            FileGroup::new(vec![PartitionedFile::new("f1.parquet".to_string(), 1024)]),
3224            FileGroup::new(vec![PartitionedFile::new("f2.parquet".to_string(), 1024)]),
3225            FileGroup::new(vec![PartitionedFile::new("f3.parquet".to_string(), 1024)]),
3226        ];
3227        let dict = |v: &str| wrap_partition_value_in_dict(ScalarValue::from(v));
3228        config.output_partitioning = output_range_partitioning_from_split_points(
3229            config.file_source.table_schema().table_schema(),
3230            config.table_partition_cols(),
3231            vec![
3232                SplitPoint::new(vec![dict("2026-09")]),
3233                SplitPoint::new(vec![dict("2026-10")]),
3234            ],
3235        )
3236        .unwrap();
3237
3238        let partitioning = config.output_partitioning();
3239        match partitioning {
3240            Partitioning::Range(range) => {
3241                assert_eq!(range.partition_count(), 3);
3242                assert_eq!(range.ordering().len(), 1);
3243                let sort_expr = &range.ordering()[0];
3244                assert_eq!(
3245                    sort_expr.expr.downcast_ref::<Column>().unwrap().name(),
3246                    "date"
3247                );
3248                assert_eq!(sort_expr.options, arrow::compute::SortOptions::default());
3249                assert_eq!(range.split_points().len(), 2);
3250            }
3251            other => panic!("Expected Range partitioning, got {other}"),
3252        }
3253
3254        let err = output_range_partitioning_from_split_points(
3255            config.file_source.table_schema().table_schema(),
3256            config.table_partition_cols(),
3257            vec![
3258                SplitPoint::new(vec![dict("2026-10")]),
3259                SplitPoint::new(vec![dict("2026-09")]),
3260            ],
3261        )
3262        .unwrap_err();
3263        assert!(err.to_string().contains("strictly ordered"), "{err}");
3264
3265        // Test multiple partition columns
3266        let multiple_partition_cols = vec![
3267            Field::new("year", wrap_partition_type_in_dict(DataType::Utf8), false),
3268            Field::new("month", wrap_partition_type_in_dict(DataType::Utf8), false),
3269        ];
3270
3271        config = config_for_projection(
3272            Arc::clone(&file_schema),
3273            None,
3274            Statistics::new_unknown(&file_schema),
3275            multiple_partition_cols,
3276        );
3277        config.file_groups = vec![
3278            FileGroup::new(vec![PartitionedFile::new("f1.parquet".to_string(), 1024)]),
3279            FileGroup::new(vec![PartitionedFile::new("f2.parquet".to_string(), 1024)]),
3280        ];
3281        config.output_partitioning = output_range_partitioning_from_split_points(
3282            config.file_source.table_schema().table_schema(),
3283            config.table_partition_cols(),
3284            vec![SplitPoint::new(vec![dict("2026"), dict("09")])],
3285        )
3286        .unwrap();
3287
3288        let partitioning = config.output_partitioning();
3289        match partitioning {
3290            Partitioning::Range(range) => {
3291                assert_eq!(range.partition_count(), 2);
3292                let col_names: Vec<_> = range
3293                    .ordering()
3294                    .iter()
3295                    .map(|e| e.expr.downcast_ref::<Column>().unwrap().name())
3296                    .collect();
3297                assert_eq!(col_names, vec!["year", "month"]);
3298            }
3299            other => panic!("Expected Range partitioning, got {other}"),
3300        }
3301    }
3302
3303    #[test]
3304    fn try_pushdown_sort_reverses_file_groups_only_when_requested_is_reverse()
3305    -> Result<()> {
3306        let file_schema =
3307            Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, true)]));
3308
3309        let table_schema = TableSchema::from(&file_schema);
3310        let file_source = Arc::new(InexactSortPushdownSource::new(table_schema));
3311
3312        let file_groups = vec![FileGroup::new(vec![
3313            PartitionedFile::new("file1", 1),
3314            PartitionedFile::new("file2", 1),
3315        ])];
3316
3317        let sort_expr_asc = PhysicalSortExpr::new_default(Arc::new(Column::new("a", 0)));
3318        let config =
3319            FileScanConfigBuilder::new(ObjectStoreUrl::local_filesystem(), file_source)
3320                .with_file_groups(file_groups)
3321                .with_output_ordering(vec![
3322                    LexOrdering::new(vec![sort_expr_asc.clone()]).unwrap(),
3323                ])
3324                .build();
3325
3326        let requested_asc = vec![sort_expr_asc.clone()];
3327        let result = config.try_pushdown_sort(&requested_asc)?;
3328        let SortOrderPushdownResult::Inexact { inner } = result else {
3329            panic!("Expected Inexact result");
3330        };
3331        let pushed_config = inner
3332            .downcast_ref::<FileScanConfig>()
3333            .expect("Expected FileScanConfig");
3334        let pushed_files = pushed_config.file_groups[0].files();
3335        assert_eq!(pushed_files[0].object_meta.location.as_ref(), "file1");
3336        assert_eq!(pushed_files[1].object_meta.location.as_ref(), "file2");
3337
3338        let requested_desc = vec![sort_expr_asc.reverse()];
3339        let result = config.try_pushdown_sort(&requested_desc)?;
3340        let SortOrderPushdownResult::Inexact { inner } = result else {
3341            panic!("Expected Inexact result");
3342        };
3343        let pushed_config = inner
3344            .downcast_ref::<FileScanConfig>()
3345            .expect("Expected FileScanConfig");
3346        let pushed_files = pushed_config.file_groups[0].files();
3347        assert_eq!(pushed_files[0].object_meta.location.as_ref(), "file2");
3348        assert_eq!(pushed_files[1].object_meta.location.as_ref(), "file1");
3349
3350        Ok(())
3351    }
3352
3353    fn make_file_with_stats(name: &str, min: f64, max: f64) -> PartitionedFile {
3354        PartitionedFile::new(name.to_string(), 1024).with_statistics(Arc::new(
3355            Statistics {
3356                num_rows: Precision::Exact(100),
3357                total_byte_size: Precision::Exact(1024),
3358                column_statistics: vec![ColumnStatistics {
3359                    null_count: Precision::Exact(0),
3360                    min_value: Precision::Exact(ScalarValue::Float64(Some(min))),
3361                    max_value: Precision::Exact(ScalarValue::Float64(Some(max))),
3362                    ..Default::default()
3363                }],
3364            },
3365        ))
3366    }
3367
3368    fn ordered_scan_with_groups(file_groups: Vec<FileGroup>) -> FileScanConfig {
3369        let schema =
3370            Arc::new(Schema::new(vec![Field::new("a", DataType::Float64, true)]));
3371        let sort_expr = PhysicalSortExpr::new_default(Arc::new(Column::new("a", 0)));
3372        FileScanConfigBuilder::new(
3373            ObjectStoreUrl::local_filesystem(),
3374            Arc::new(MockSource::new(schema)),
3375        )
3376        .with_file_groups(file_groups)
3377        .with_output_ordering(vec![LexOrdering::new(vec![sort_expr]).unwrap()])
3378        .build()
3379    }
3380
3381    fn sized_file_with_stats(
3382        name: &str,
3383        size: u64,
3384        min: f64,
3385        max: f64,
3386    ) -> PartitionedFile {
3387        let mut file = make_file_with_stats(name, min, max);
3388        file.object_meta.size = size;
3389        file
3390    }
3391
3392    /// The files of each group, with whether each file reads only a range
3393    fn group_files(config: &FileScanConfig) -> Vec<Vec<(&str, bool)>> {
3394        config
3395            .file_groups
3396            .iter()
3397            .map(|group| {
3398                group
3399                    .iter()
3400                    .map(|f| (f.object_meta.location.as_ref(), f.range.is_some()))
3401                    .collect()
3402            })
3403            .collect()
3404    }
3405
3406    fn group_sizes(config: &FileScanConfig) -> Vec<u64> {
3407        config
3408            .file_groups
3409            .iter()
3410            .map(|group| group.iter().map(|f| f.effective_size()).sum())
3411            .collect()
3412    }
3413
3414    /// An ordered scan whose files are sorted across groups gets the same
3415    /// size-balanced split as an unordered scan and keeps its ordering.
3416    #[test]
3417    fn repartition_balances_ordered_groups() -> Result<()> {
3418        let config = ordered_scan_with_groups(vec![
3419            FileGroup::new(vec![
3420                sized_file_with_stats("f1", 8000, 0.0, 9.0),
3421                sized_file_with_stats("f2", 8000, 10.0, 19.0),
3422            ]),
3423            FileGroup::new(vec![
3424                sized_file_with_stats("f3", 1000, 20.0, 29.0),
3425                sized_file_with_stats("f4", 1000, 30.0, 39.0),
3426            ]),
3427        ]);
3428        let ordering = config.output_ordering.first().cloned();
3429        assert_eq!(group_sizes(&config), vec![16000, 2000]);
3430
3431        let repartitioned = DataSource::repartitioned(&config, 4, 0, ordering)?
3432            .expect("ordered groups should be rebalanced");
3433        let repartitioned = repartitioned
3434            .downcast_ref::<FileScanConfig>()
3435            .expect("expected FileScanConfig");
3436        assert_eq!(group_sizes(repartitioned), vec![4500, 4500, 4500, 4500]);
3437        assert_eq!(
3438            repartitioned.validated_output_ordering(),
3439            config.validated_output_ordering()
3440        );
3441        Ok(())
3442    }
3443
3444    /// If moving the group boundaries would put overlapping files in one
3445    /// group, the scan keeps its groups and its ordering.
3446    #[test]
3447    fn repartition_keeps_ordered_groups_when_rebalancing_breaks_order() -> Result<()> {
3448        let config = ordered_scan_with_groups(vec![
3449            FileGroup::new(vec![
3450                sized_file_with_stats("f1", 8000, 0.0, 9.0),
3451                sized_file_with_stats("f2", 8000, 10.0, 19.0),
3452            ]),
3453            FileGroup::new(vec![
3454                sized_file_with_stats("f3", 1000, 5.0, 15.0),
3455                sized_file_with_stats("f4", 1000, 16.0, 25.0),
3456            ]),
3457        ]);
3458        let ordering = config.output_ordering.first().cloned();
3459        assert_eq!(config.validated_output_ordering().len(), 1);
3460
3461        assert!(DataSource::repartitioned(&config, 4, 0, ordering)?.is_none());
3462        Ok(())
3463    }
3464
3465    /// With `NULLS FIRST`, a file with NULLs can only be the first file of a
3466    /// group, so a size-balanced split that puts it after another file is not
3467    /// used.
3468    #[test]
3469    fn repartition_keeps_ordered_groups_when_rebalancing_misplaces_nulls() -> Result<()> {
3470        let mut with_nulls = sized_file_with_stats("f2", 1000, 10.0, 19.0);
3471        Arc::make_mut(with_nulls.statistics.as_mut().unwrap()).column_statistics[0]
3472            .null_count = Precision::Exact(1);
3473        let config = ordered_scan_with_groups(vec![
3474            FileGroup::new(vec![sized_file_with_stats("f1", 8000, 0.0, 9.0)]),
3475            FileGroup::new(vec![with_nulls]),
3476        ]);
3477        let ordering = config.output_ordering.first().cloned();
3478        assert_eq!(config.validated_output_ordering().len(), 1);
3479
3480        let repartitioned = DataSource::repartitioned(&config, 4, 0, ordering)?
3481            .expect("the large file should be split");
3482        let repartitioned = repartitioned
3483            .downcast_ref::<FileScanConfig>()
3484            .expect("expected FileScanConfig");
3485        assert_eq!(
3486            group_files(repartitioned),
3487            vec![
3488                vec![("f1", true)],
3489                vec![("f2", true)],
3490                vec![("f1", true)],
3491                vec![("f1", true)],
3492            ]
3493        );
3494        assert_eq!(
3495            repartitioned.validated_output_ordering(),
3496            config.validated_output_ordering()
3497        );
3498        Ok(())
3499    }
3500
3501    /// If moving the group boundaries would put overlapping files in one
3502    /// group, the ordered split is used instead: it keeps multi-file groups
3503    /// and only splits single-file groups.
3504    #[test]
3505    fn repartition_falls_back_to_ordered_split_when_rebalancing_breaks_order()
3506    -> Result<()> {
3507        let config = ordered_scan_with_groups(vec![
3508            FileGroup::new(vec![
3509                sized_file_with_stats("f1", 8000, 0.0, 9.0),
3510                sized_file_with_stats("f2", 8000, 10.0, 19.0),
3511            ]),
3512            FileGroup::new(vec![sized_file_with_stats("f3", 1000, 5.0, 15.0)]),
3513        ]);
3514        let ordering = config.output_ordering.first().cloned();
3515        assert_eq!(config.validated_output_ordering().len(), 1);
3516
3517        let repartitioned = DataSource::repartitioned(&config, 4, 0, ordering)?
3518            .expect("the single-file group should be split");
3519        let repartitioned = repartitioned
3520            .downcast_ref::<FileScanConfig>()
3521            .expect("expected FileScanConfig");
3522        assert_eq!(
3523            group_files(repartitioned),
3524            vec![
3525                vec![("f1", false), ("f2", false)],
3526                vec![("f3", true)],
3527                vec![("f3", true)],
3528                vec![("f3", true)],
3529            ]
3530        );
3531        assert_eq!(
3532            repartitioned.validated_output_ordering(),
3533            config.validated_output_ordering()
3534        );
3535        Ok(())
3536    }
3537
3538    fn make_exact_empty_file(name: &str) -> PartitionedFile {
3539        PartitionedFile::new(name.to_string(), 1024).with_statistics(Arc::new(
3540            Statistics {
3541                num_rows: Precision::Exact(0),
3542                ..Default::default()
3543            },
3544        ))
3545    }
3546
3547    #[derive(Clone)]
3548    struct ExactSortPushdownSource {
3549        metrics: ExecutionPlanMetricsSet,
3550        table_schema: TableSchema,
3551    }
3552
3553    impl ExactSortPushdownSource {
3554        fn new(table_schema: TableSchema) -> Self {
3555            Self {
3556                metrics: ExecutionPlanMetricsSet::new(),
3557                table_schema,
3558            }
3559        }
3560    }
3561
3562    impl FileSource for ExactSortPushdownSource {
3563        fn create_file_opener(
3564            &self,
3565            _object_store: Arc<dyn ObjectStore>,
3566            _base_config: &FileScanConfig,
3567            _partition: usize,
3568        ) -> Result<Arc<dyn crate::file_stream::FileOpener>> {
3569            unimplemented!()
3570        }
3571
3572        fn table_schema(&self) -> &TableSchema {
3573            &self.table_schema
3574        }
3575
3576        fn with_batch_size(&self, _batch_size: usize) -> Arc<dyn FileSource> {
3577            Arc::new(self.clone())
3578        }
3579
3580        fn metrics(&self) -> &ExecutionPlanMetricsSet {
3581            &self.metrics
3582        }
3583
3584        fn file_type(&self) -> &str {
3585            "mock_exact"
3586        }
3587
3588        fn try_pushdown_sort(
3589            &self,
3590            _order: &[PhysicalSortExpr],
3591            _eq_properties: &EquivalenceProperties,
3592        ) -> Result<SortOrderPushdownResult<Arc<dyn FileSource>>> {
3593            Ok(SortOrderPushdownResult::Exact {
3594                inner: Arc::new(self.clone()) as Arc<dyn FileSource>,
3595            })
3596        }
3597
3598        fn apply_expressions(
3599            &self,
3600            _f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
3601        ) -> Result<TreeNodeRecursion> {
3602            Ok(TreeNodeRecursion::Continue)
3603        }
3604    }
3605
3606    #[test]
3607    fn sort_pushdown_unsupported_source_files_get_sorted() -> Result<()> {
3608        let file_schema =
3609            Arc::new(Schema::new(vec![Field::new("a", DataType::Float64, false)]));
3610        let table_schema = TableSchema::from(&file_schema);
3611        let file_source = Arc::new(MockSource::new(table_schema));
3612
3613        let file_groups = vec![FileGroup::new(vec![
3614            make_file_with_stats("file3", 20.0, 30.0),
3615            make_file_with_stats("file1", 0.0, 9.0),
3616            make_file_with_stats("file2", 10.0, 19.0),
3617        ])];
3618
3619        let sort_expr = PhysicalSortExpr::new_default(Arc::new(Column::new("a", 0)));
3620        let config =
3621            FileScanConfigBuilder::new(ObjectStoreUrl::local_filesystem(), file_source)
3622                .with_file_groups(file_groups)
3623                .build();
3624
3625        let result = config.try_pushdown_sort(&[sort_expr])?;
3626        let SortOrderPushdownResult::Inexact { inner } = result else {
3627            panic!("Expected Inexact result, got {result:?}");
3628        };
3629        let pushed_config = inner
3630            .downcast_ref::<FileScanConfig>()
3631            .expect("Expected FileScanConfig");
3632        let files = pushed_config.file_groups[0].files();
3633        assert_eq!(files[0].object_meta.location.as_ref(), "file1");
3634        assert_eq!(files[1].object_meta.location.as_ref(), "file2");
3635        assert_eq!(files[2].object_meta.location.as_ref(), "file3");
3636        assert!(pushed_config.output_ordering.is_empty());
3637        Ok(())
3638    }
3639
3640    #[test]
3641    fn sort_pushdown_unsupported_source_already_sorted() -> Result<()> {
3642        let file_schema =
3643            Arc::new(Schema::new(vec![Field::new("a", DataType::Float64, false)]));
3644        let table_schema = TableSchema::from(&file_schema);
3645        let file_source = Arc::new(MockSource::new(table_schema));
3646
3647        let file_groups = vec![FileGroup::new(vec![
3648            make_file_with_stats("file1", 0.0, 9.0),
3649            make_file_with_stats("file2", 10.0, 19.0),
3650            make_file_with_stats("file3", 20.0, 30.0),
3651        ])];
3652
3653        let sort_expr = PhysicalSortExpr::new_default(Arc::new(Column::new("a", 0)));
3654        let config =
3655            FileScanConfigBuilder::new(ObjectStoreUrl::local_filesystem(), file_source)
3656                .with_file_groups(file_groups)
3657                .build();
3658
3659        let result = config.try_pushdown_sort(&[sort_expr])?;
3660        assert!(matches!(result, SortOrderPushdownResult::Unsupported));
3661        Ok(())
3662    }
3663
3664    #[test]
3665    fn sort_pushdown_unsupported_source_descending_sort() -> Result<()> {
3666        let file_schema =
3667            Arc::new(Schema::new(vec![Field::new("a", DataType::Float64, false)]));
3668        let table_schema = TableSchema::from(&file_schema);
3669        let file_source = Arc::new(MockSource::new(table_schema));
3670
3671        let file_groups = vec![FileGroup::new(vec![
3672            make_file_with_stats("file1", 0.0, 9.0),
3673            make_file_with_stats("file3", 20.0, 30.0),
3674            make_file_with_stats("file2", 10.0, 19.0),
3675        ])];
3676
3677        let sort_expr = PhysicalSortExpr::new(
3678            Arc::new(Column::new("a", 0)),
3679            arrow::compute::SortOptions {
3680                descending: true,
3681                nulls_first: true,
3682            },
3683        );
3684        let config =
3685            FileScanConfigBuilder::new(ObjectStoreUrl::local_filesystem(), file_source)
3686                .with_file_groups(file_groups)
3687                .build();
3688
3689        let result = config.try_pushdown_sort(&[sort_expr])?;
3690        let SortOrderPushdownResult::Inexact { inner } = result else {
3691            panic!("Expected Inexact result");
3692        };
3693        let pushed_config = inner
3694            .downcast_ref::<FileScanConfig>()
3695            .expect("Expected FileScanConfig");
3696        let files = pushed_config.file_groups[0].files();
3697        assert_eq!(files[0].object_meta.location.as_ref(), "file3");
3698        assert_eq!(files[1].object_meta.location.as_ref(), "file2");
3699        assert_eq!(files[2].object_meta.location.as_ref(), "file1");
3700        Ok(())
3701    }
3702
3703    #[test]
3704    fn sort_pushdown_exact_source_non_overlapping_returns_exact() -> Result<()> {
3705        let file_schema =
3706            Arc::new(Schema::new(vec![Field::new("a", DataType::Float64, false)]));
3707        let table_schema = TableSchema::from(&file_schema);
3708        let file_source = Arc::new(ExactSortPushdownSource::new(table_schema));
3709
3710        let sort_expr = PhysicalSortExpr::new_default(Arc::new(Column::new("a", 0)));
3711
3712        let file_groups = vec![FileGroup::new(vec![
3713            make_file_with_stats("file1", 0.0, 9.0),
3714            make_file_with_stats("file2", 10.0, 19.0),
3715            make_file_with_stats("file3", 20.0, 30.0),
3716        ])];
3717
3718        let config =
3719            FileScanConfigBuilder::new(ObjectStoreUrl::local_filesystem(), file_source)
3720                .with_file_groups(file_groups)
3721                .with_output_ordering(vec![
3722                    LexOrdering::new(vec![sort_expr.clone()]).unwrap(),
3723                ])
3724                .build();
3725
3726        let result = config.try_pushdown_sort(&[sort_expr])?;
3727        let SortOrderPushdownResult::Exact { inner } = result else {
3728            panic!("Expected Exact result, got {result:?}");
3729        };
3730        let pushed_config = inner
3731            .downcast_ref::<FileScanConfig>()
3732            .expect("Expected FileScanConfig");
3733        assert!(!pushed_config.output_ordering.is_empty());
3734        Ok(())
3735    }
3736
3737    #[test]
3738    fn sort_pushdown_exact_source_overlapping_downgraded_to_inexact() -> Result<()> {
3739        let file_schema =
3740            Arc::new(Schema::new(vec![Field::new("a", DataType::Float64, false)]));
3741        let table_schema = TableSchema::from(&file_schema);
3742        let file_source = Arc::new(ExactSortPushdownSource::new(table_schema));
3743
3744        let sort_expr = PhysicalSortExpr::new_default(Arc::new(Column::new("a", 0)));
3745
3746        let file_groups = vec![FileGroup::new(vec![
3747            make_file_with_stats("file1", 0.0, 15.0),
3748            make_file_with_stats("file2", 10.0, 25.0),
3749            make_file_with_stats("file3", 20.0, 30.0),
3750        ])];
3751
3752        let config =
3753            FileScanConfigBuilder::new(ObjectStoreUrl::local_filesystem(), file_source)
3754                .with_file_groups(file_groups)
3755                .with_output_ordering(vec![
3756                    LexOrdering::new(vec![sort_expr.clone()]).unwrap(),
3757                ])
3758                .build();
3759
3760        let result = config.try_pushdown_sort(&[sort_expr])?;
3761        let SortOrderPushdownResult::Inexact { inner } = result else {
3762            panic!("Expected Inexact (downgraded), got {result:?}");
3763        };
3764        let pushed_config = inner
3765            .downcast_ref::<FileScanConfig>()
3766            .expect("Expected FileScanConfig");
3767        assert!(pushed_config.output_ordering.is_empty());
3768        Ok(())
3769    }
3770
3771    #[test]
3772    fn sort_pushdown_exact_source_out_of_order_returns_exact() -> Result<()> {
3773        let file_schema =
3774            Arc::new(Schema::new(vec![Field::new("a", DataType::Float64, false)]));
3775        let table_schema = TableSchema::from(&file_schema);
3776        let file_source = Arc::new(ExactSortPushdownSource::new(table_schema));
3777
3778        let sort_expr = PhysicalSortExpr::new_default(Arc::new(Column::new("a", 0)));
3779
3780        let file_groups = vec![FileGroup::new(vec![
3781            make_file_with_stats("file3", 20.0, 30.0),
3782            make_file_with_stats("file1", 0.0, 9.0),
3783            make_file_with_stats("file2", 10.0, 19.0),
3784        ])];
3785
3786        let config =
3787            FileScanConfigBuilder::new(ObjectStoreUrl::local_filesystem(), file_source)
3788                .with_file_groups(file_groups)
3789                .with_output_ordering(vec![
3790                    LexOrdering::new(vec![sort_expr.clone()]).unwrap(),
3791                ])
3792                .build();
3793
3794        let result = config.try_pushdown_sort(&[sort_expr])?;
3795        let SortOrderPushdownResult::Exact { inner } = result else {
3796            panic!("Expected Exact result, got {result:?}");
3797        };
3798        let pushed_config = inner
3799            .downcast_ref::<FileScanConfig>()
3800            .expect("Expected FileScanConfig");
3801        let files = pushed_config.file_groups[0].files();
3802        assert_eq!(files[0].object_meta.location.as_ref(), "file1");
3803        assert_eq!(files[1].object_meta.location.as_ref(), "file2");
3804        assert_eq!(files[2].object_meta.location.as_ref(), "file3");
3805        assert!(!pushed_config.output_ordering.is_empty());
3806        Ok(())
3807    }
3808
3809    #[test]
3810    fn sort_pushdown_unsupported_source_single_file_groups() -> Result<()> {
3811        let file_schema =
3812            Arc::new(Schema::new(vec![Field::new("a", DataType::Float64, false)]));
3813        let table_schema = TableSchema::from(&file_schema);
3814        let file_source = Arc::new(MockSource::new(table_schema));
3815
3816        let file_groups = vec![
3817            FileGroup::new(vec![make_file_with_stats("file1", 0.0, 9.0)]),
3818            FileGroup::new(vec![make_file_with_stats("file2", 10.0, 19.0)]),
3819        ];
3820
3821        let sort_expr = PhysicalSortExpr::new_default(Arc::new(Column::new("a", 0)));
3822        let config =
3823            FileScanConfigBuilder::new(ObjectStoreUrl::local_filesystem(), file_source)
3824                .with_file_groups(file_groups)
3825                .build();
3826
3827        let result = config.try_pushdown_sort(&[sort_expr])?;
3828        assert!(
3829            matches!(result, SortOrderPushdownResult::Unsupported),
3830            "Expected Unsupported for single-file groups"
3831        );
3832        Ok(())
3833    }
3834
3835    #[test]
3836    fn sort_pushdown_unsupported_source_multiple_groups() -> Result<()> {
3837        let file_schema =
3838            Arc::new(Schema::new(vec![Field::new("a", DataType::Float64, false)]));
3839        let table_schema = TableSchema::from(&file_schema);
3840        let file_source = Arc::new(MockSource::new(table_schema));
3841
3842        let file_groups = vec![
3843            FileGroup::new(vec![
3844                make_file_with_stats("file_b", 10.0, 19.0),
3845                make_file_with_stats("file_a", 0.0, 9.0),
3846            ]),
3847            FileGroup::new(vec![
3848                make_file_with_stats("file_d", 30.0, 39.0),
3849                make_file_with_stats("file_c", 20.0, 29.0),
3850            ]),
3851        ];
3852
3853        let sort_expr = PhysicalSortExpr::new_default(Arc::new(Column::new("a", 0)));
3854        let config =
3855            FileScanConfigBuilder::new(ObjectStoreUrl::local_filesystem(), file_source)
3856                .with_file_groups(file_groups)
3857                .build();
3858
3859        let result = config.try_pushdown_sort(&[sort_expr])?;
3860        let SortOrderPushdownResult::Inexact { inner } = result else {
3861            panic!("Expected Inexact result");
3862        };
3863        let pushed_config = inner
3864            .downcast_ref::<FileScanConfig>()
3865            .expect("Expected FileScanConfig");
3866        let files0 = pushed_config.file_groups[0].files();
3867        assert_eq!(files0[0].object_meta.location.as_ref(), "file_a");
3868        assert_eq!(files0[1].object_meta.location.as_ref(), "file_b");
3869        let files1 = pushed_config.file_groups[1].files();
3870        assert_eq!(files1[0].object_meta.location.as_ref(), "file_c");
3871        assert_eq!(files1[1].object_meta.location.as_ref(), "file_d");
3872        Ok(())
3873    }
3874
3875    #[test]
3876    fn sort_pushdown_unsupported_source_partial_statistics() -> Result<()> {
3877        let file_schema =
3878            Arc::new(Schema::new(vec![Field::new("a", DataType::Float64, false)]));
3879        let table_schema = TableSchema::from(&file_schema);
3880        let file_source = Arc::new(MockSource::new(table_schema));
3881
3882        let file_groups = vec![
3883            FileGroup::new(vec![
3884                make_file_with_stats("file_b", 10.0, 19.0),
3885                make_file_with_stats("file_a", 0.0, 9.0),
3886            ]),
3887            FileGroup::new(vec![
3888                PartitionedFile::new("file_d".to_string(), 1024),
3889                PartitionedFile::new("file_c".to_string(), 1024),
3890            ]),
3891        ];
3892
3893        let sort_expr = PhysicalSortExpr::new_default(Arc::new(Column::new("a", 0)));
3894        let config =
3895            FileScanConfigBuilder::new(ObjectStoreUrl::local_filesystem(), file_source)
3896                .with_file_groups(file_groups)
3897                .build();
3898
3899        let result = config.try_pushdown_sort(&[sort_expr])?;
3900        let SortOrderPushdownResult::Inexact { inner } = result else {
3901            panic!("Expected Inexact result");
3902        };
3903        let pushed_config = inner
3904            .downcast_ref::<FileScanConfig>()
3905            .expect("Expected FileScanConfig");
3906        let files0 = pushed_config.file_groups[0].files();
3907        assert_eq!(files0[0].object_meta.location.as_ref(), "file_a");
3908        assert_eq!(files0[1].object_meta.location.as_ref(), "file_b");
3909        let files1 = pushed_config.file_groups[1].files();
3910        assert_eq!(files1[0].object_meta.location.as_ref(), "file_d");
3911        assert_eq!(files1[1].object_meta.location.as_ref(), "file_c");
3912        Ok(())
3913    }
3914
3915    #[test]
3916    fn sort_pushdown_inexact_source_with_statistics_sorting() -> Result<()> {
3917        let file_schema =
3918            Arc::new(Schema::new(vec![Field::new("a", DataType::Float64, false)]));
3919        let table_schema = TableSchema::from(&file_schema);
3920        let file_source = Arc::new(InexactSortPushdownSource::new(table_schema));
3921
3922        let file_groups = vec![FileGroup::new(vec![
3923            make_file_with_stats("file2", 10.0, 19.0),
3924            make_file_with_stats("file1", 0.0, 9.0),
3925        ])];
3926
3927        let sort_expr = PhysicalSortExpr::new_default(Arc::new(Column::new("a", 0)));
3928        let config =
3929            FileScanConfigBuilder::new(ObjectStoreUrl::local_filesystem(), file_source)
3930                .with_file_groups(file_groups)
3931                .build();
3932
3933        let result = config.try_pushdown_sort(&[sort_expr])?;
3934        let SortOrderPushdownResult::Inexact { inner } = result else {
3935            panic!("Expected Inexact result");
3936        };
3937        let pushed_config = inner
3938            .downcast_ref::<FileScanConfig>()
3939            .expect("Expected FileScanConfig");
3940        let files = pushed_config.file_groups[0].files();
3941        assert_eq!(files[0].object_meta.location.as_ref(), "file1");
3942        assert_eq!(files[1].object_meta.location.as_ref(), "file2");
3943        assert!(pushed_config.output_ordering.is_empty());
3944        Ok(())
3945    }
3946
3947    #[test]
3948    fn sort_pushdown_exact_multi_group_preserves_parallelism() -> Result<()> {
3949        // ExactSortPushdownSource + 4 non-overlapping files in 2 interleaved groups.
3950        // Groups should NOT be redistributed — interleaved groups allow SPM to
3951        // pull from both partitions concurrently, keeping parallel I/O active.
3952        // Redistributing consecutively would make SPM read one partition at a
3953        // time (all values in group 0 < group 1), degrading to single-threaded I/O.
3954        let file_schema =
3955            Arc::new(Schema::new(vec![Field::new("a", DataType::Float64, false)]));
3956        let table_schema = TableSchema::from(&file_schema);
3957        let file_source = Arc::new(ExactSortPushdownSource::new(table_schema));
3958
3959        let sort_expr = PhysicalSortExpr::new_default(Arc::new(Column::new("a", 0)));
3960
3961        // 2 groups with interleaved ranges (simulating bin-packing result):
3962        // Group 0: [file_01(0-9), file_03(20-29)]
3963        // Group 1: [file_02(10-19), file_04(30-39)]
3964        let file_groups = vec![
3965            FileGroup::new(vec![
3966                make_file_with_stats("file_01", 0.0, 9.0),
3967                make_file_with_stats("file_03", 20.0, 29.0),
3968            ]),
3969            FileGroup::new(vec![
3970                make_file_with_stats("file_02", 10.0, 19.0),
3971                make_file_with_stats("file_04", 30.0, 39.0),
3972            ]),
3973        ];
3974
3975        let config =
3976            FileScanConfigBuilder::new(ObjectStoreUrl::local_filesystem(), file_source)
3977                .with_file_groups(file_groups)
3978                .with_output_ordering(vec![
3979                    LexOrdering::new(vec![sort_expr.clone()]).unwrap(),
3980                ])
3981                .build();
3982
3983        let result = config.try_pushdown_sort(&[sort_expr])?;
3984        let SortOrderPushdownResult::Exact { inner } = result else {
3985            panic!("Expected Exact result, got {result:?}");
3986        };
3987        let pushed_config = inner
3988            .downcast_ref::<FileScanConfig>()
3989            .expect("Expected FileScanConfig");
3990
3991        // 2 groups preserved (parallelism maintained)
3992        assert_eq!(pushed_config.file_groups.len(), 2);
3993
3994        // Files within each group are sorted by stats, but groups are NOT
3995        // redistributed — interleaved assignment from bin-packing is kept
3996        let files0 = pushed_config.file_groups[0].files();
3997        assert_eq!(files0[0].object_meta.location.as_ref(), "file_01");
3998        assert_eq!(files0[1].object_meta.location.as_ref(), "file_03");
3999        let files1 = pushed_config.file_groups[1].files();
4000        assert_eq!(files1[0].object_meta.location.as_ref(), "file_02");
4001        assert_eq!(files1[1].object_meta.location.as_ref(), "file_04");
4002
4003        // output_ordering preserved (Exact, each group internally non-overlapping)
4004        assert!(!pushed_config.output_ordering.is_empty());
4005        Ok(())
4006    }
4007
4008    #[test]
4009    fn sort_pushdown_reverse_preserves_file_order_with_stats() -> Result<()> {
4010        // Reverse scan should reverse file order but NOT apply statistics-based
4011        // sorting (which would undo the reversal). The result is Inexact.
4012        let file_schema =
4013            Arc::new(Schema::new(vec![Field::new("a", DataType::Float64, false)]));
4014        let table_schema = TableSchema::from(&file_schema);
4015        let file_source = Arc::new(InexactSortPushdownSource::new(table_schema));
4016
4017        let sort_expr = PhysicalSortExpr::new_default(Arc::new(Column::new("a", 0)));
4018
4019        // Files with stats, in ASC order. Output ordering is [a ASC].
4020        let file_groups = vec![FileGroup::new(vec![
4021            make_file_with_stats("file1", 0.0, 9.0),
4022            make_file_with_stats("file2", 10.0, 19.0),
4023            make_file_with_stats("file3", 20.0, 30.0),
4024        ])];
4025
4026        let config =
4027            FileScanConfigBuilder::new(ObjectStoreUrl::local_filesystem(), file_source)
4028                .with_file_groups(file_groups)
4029                .with_output_ordering(vec![
4030                    LexOrdering::new(vec![sort_expr.clone()]).unwrap(),
4031                ])
4032                .build();
4033
4034        // Request DESC → reverse path
4035        let result = config.try_pushdown_sort(&[sort_expr.reverse()])?;
4036        let SortOrderPushdownResult::Inexact { inner } = result else {
4037            panic!("Expected Inexact for reverse scan, got {result:?}");
4038        };
4039        let pushed_config = inner
4040            .downcast_ref::<FileScanConfig>()
4041            .expect("Expected FileScanConfig");
4042
4043        // Files should be reversed (not re-sorted by stats)
4044        let files = pushed_config.file_groups[0].files();
4045        assert_eq!(files[0].object_meta.location.as_ref(), "file3");
4046        assert_eq!(files[1].object_meta.location.as_ref(), "file2");
4047        assert_eq!(files[2].object_meta.location.as_ref(), "file1");
4048
4049        // output_ordering cleared (Inexact)
4050        assert!(pushed_config.output_ordering.is_empty());
4051        Ok(())
4052    }
4053
4054    /// Helper: create a PartitionedFile with stats including null count
4055    fn make_file_with_null_stats(
4056        name: &str,
4057        min: f64,
4058        max: f64,
4059        null_count: usize,
4060    ) -> PartitionedFile {
4061        PartitionedFile::new(name.to_string(), 1024).with_statistics(Arc::new(
4062            Statistics {
4063                num_rows: Precision::Exact(100),
4064                total_byte_size: Precision::Exact(1024),
4065                column_statistics: vec![ColumnStatistics {
4066                    null_count: Precision::Exact(null_count),
4067                    min_value: Precision::Exact(ScalarValue::Float64(Some(min))),
4068                    max_value: Precision::Exact(ScalarValue::Float64(Some(max))),
4069                    ..Default::default()
4070                }],
4071            },
4072        ))
4073    }
4074
4075    #[test]
4076    fn file_group_ordering_includes_nulls() -> Result<()> {
4077        // Arrange
4078        let schema =
4079            Arc::new(Schema::new(vec![Field::new("a", DataType::Float64, true)]));
4080        for (descending, nulls_first) in
4081            [(false, false), (false, true), (true, false), (true, true)]
4082        {
4083            let sort = PhysicalSortExpr::new(
4084                Arc::new(Column::new("a", 0)),
4085                arrow::compute::SortOptions {
4086                    descending,
4087                    nulls_first,
4088                },
4089            );
4090            for null_count in [
4091                Precision::Exact(0),
4092                Precision::Exact(1),
4093                Precision::Absent,
4094                Precision::Inexact(0),
4095            ] {
4096                let mut files = vec![
4097                    make_file_with_null_stats("low", 0.0, 9.0, 0),
4098                    make_file_with_null_stats("high", 10.0, 19.0, 0),
4099                ];
4100                for file in &mut files {
4101                    Arc::make_mut(file.statistics.as_mut().unwrap()).column_statistics
4102                        [0]
4103                    .null_count = null_count;
4104                }
4105                if descending {
4106                    files.reverse();
4107                }
4108                let config = FileScanConfigBuilder::new(
4109                    ObjectStoreUrl::local_filesystem(),
4110                    Arc::new(MockSource::new(TableSchema::from(&schema))),
4111                )
4112                .with_file_groups(vec![FileGroup::new(files)])
4113                .with_output_ordering(vec![[sort.clone()].into()])
4114                .build();
4115
4116                // Act
4117                let ordered = config.eq_properties().ordering_satisfy([sort.clone()])?;
4118
4119                // Assert
4120                assert_eq!(
4121                    ordered,
4122                    null_count == Precision::Exact(0),
4123                    "descending={descending}, nulls_first={nulls_first}, null_count={null_count:?}"
4124                );
4125            }
4126        }
4127        Ok(())
4128    }
4129
4130    #[test]
4131    fn file_group_ordering_with_all_null_or_empty_file() -> Result<()> {
4132        // Arrange
4133        let schema =
4134            Arc::new(Schema::new(vec![Field::new("a", DataType::Float64, true)]));
4135        for (descending, nulls_first) in
4136            [(false, false), (false, true), (true, false), (true, true)]
4137        {
4138            let sort = PhysicalSortExpr::new(
4139                Arc::new(Column::new("a", 0)),
4140                arrow::compute::SortOptions {
4141                    descending,
4142                    nulls_first,
4143                },
4144            );
4145            for (num_rows, file_first) in [(0, false), (0, true), (2, false), (2, true)] {
4146                let file = PartitionedFile::new("nulls_or_empty", 1024).with_statistics(
4147                    Arc::new(Statistics {
4148                        num_rows: Precision::Exact(num_rows),
4149                        column_statistics: vec![ColumnStatistics {
4150                            null_count: Precision::Exact(num_rows),
4151                            ..Default::default()
4152                        }],
4153                        ..Default::default()
4154                    }),
4155                );
4156                let mut files =
4157                    vec![file, make_file_with_null_stats("non_null", 1.0, 2.0, 0)];
4158                if !file_first {
4159                    files.reverse();
4160                }
4161                let config = FileScanConfigBuilder::new(
4162                    ObjectStoreUrl::local_filesystem(),
4163                    Arc::new(MockSource::new(TableSchema::from(&schema))),
4164                )
4165                .with_file_groups(vec![FileGroup::new(files)])
4166                .with_output_ordering(vec![[sort.clone()].into()])
4167                .build();
4168
4169                // Act
4170                let ordered = config.eq_properties().ordering_satisfy([sort.clone()])?;
4171
4172                // Assert
4173                assert_eq!(
4174                    ordered,
4175                    num_rows == 0 || file_first == nulls_first,
4176                    "descending={descending}, nulls_first={nulls_first}, num_rows={num_rows}, file_first={file_first}"
4177                );
4178            }
4179        }
4180        Ok(())
4181    }
4182
4183    #[test]
4184    fn sort_pushdown_unsupported_with_nulls_does_not_upgrade_to_exact() -> Result<()> {
4185        // Files are non-overlapping but one has NULLs.
4186        // Should NOT upgrade to Exact — NULLs would appear in wrong position.
4187        let file_schema =
4188            Arc::new(Schema::new(vec![Field::new("a", DataType::Float64, true)]));
4189        let table_schema = TableSchema::from(&file_schema);
4190        let file_source = Arc::new(MockSource::new(table_schema));
4191
4192        let sort_expr = PhysicalSortExpr::new_default(Arc::new(Column::new("a", 0)));
4193
4194        // Files in wrong order (high min first) to trigger reordering
4195        let file_groups = vec![FileGroup::new(vec![
4196            make_file_with_null_stats("b_no_nulls", 10.0, 19.0, 0),
4197            make_file_with_null_stats("a_with_nulls", 0.0, 9.0, 5), // has NULLs
4198        ])];
4199
4200        let config =
4201            FileScanConfigBuilder::new(ObjectStoreUrl::local_filesystem(), file_source)
4202                .with_file_groups(file_groups)
4203                .with_output_ordering(vec![
4204                    LexOrdering::new(vec![sort_expr.clone()]).unwrap(),
4205                ])
4206                .build();
4207
4208        let result = config.try_pushdown_sort(&[sort_expr])?;
4209        // Should be Inexact (not Exact) because of NULLs
4210        assert!(
4211            matches!(result, SortOrderPushdownResult::Inexact { .. }),
4212            "Expected Inexact due to NULLs, got {result:?}"
4213        );
4214        Ok(())
4215    }
4216
4217    #[test]
4218    fn sort_pushdown_unsupported_no_nulls_upgrades_to_exact() -> Result<()> {
4219        // Files are non-overlapping, no NULLs → should upgrade to Exact
4220        let file_schema =
4221            Arc::new(Schema::new(vec![Field::new("a", DataType::Float64, true)]));
4222        let table_schema = TableSchema::from(&file_schema);
4223        let file_source = Arc::new(MockSource::new(table_schema));
4224
4225        let sort_expr = PhysicalSortExpr::new_default(Arc::new(Column::new("a", 0)));
4226
4227        let file_groups = vec![FileGroup::new(vec![
4228            make_file_with_null_stats("b_high", 10.0, 19.0, 0),
4229            make_file_with_null_stats("a_low", 0.0, 9.0, 0),
4230        ])];
4231
4232        let config =
4233            FileScanConfigBuilder::new(ObjectStoreUrl::local_filesystem(), file_source)
4234                .with_file_groups(file_groups)
4235                .with_output_ordering(vec![
4236                    LexOrdering::new(vec![sort_expr.clone()]).unwrap(),
4237                ])
4238                .build();
4239
4240        let result = config.try_pushdown_sort(&[sort_expr])?;
4241        assert!(
4242            matches!(result, SortOrderPushdownResult::Exact { .. }),
4243            "Expected Exact (no NULLs), got {result:?}"
4244        );
4245        Ok(())
4246    }
4247
4248    /// Helper: build a `ProjectionExprs` from `(expr, alias)` pairs.
4249    fn make_projection(pairs: Vec<(Arc<dyn PhysicalExpr>, &str)>) -> ProjectionExprs {
4250        ProjectionExprs::new(
4251            pairs
4252                .into_iter()
4253                .map(|(expr, alias)| ProjectionExpr::new(expr, alias)),
4254        )
4255    }
4256
4257    /// Helper: create a volatile (non-deterministic) function expression,
4258    /// e.g. `random()`.
4259    fn make_volatile_expr() -> Arc<dyn PhysicalExpr> {
4260        use datafusion_common::config::ConfigOptions;
4261        use datafusion_expr::ScalarUDF;
4262        use datafusion_functions::math::random::RandomFunc;
4263        use datafusion_physical_expr::ScalarFunctionExpr;
4264
4265        Arc::new(ScalarFunctionExpr::new(
4266            "random",
4267            Arc::new(ScalarUDF::from(RandomFunc::new())),
4268            vec![],
4269            Arc::new(Field::new("random", DataType::Float64, false)),
4270            Arc::new(ConfigOptions::default()),
4271        ))
4272    }
4273
4274    /// Helper: create a deterministic but expensive scalar-function
4275    /// expression, e.g. `abs(<arg>)`.
4276    fn make_udf_expr(args: Vec<Arc<dyn PhysicalExpr>>) -> Arc<dyn PhysicalExpr> {
4277        use datafusion_common::config::ConfigOptions;
4278        use datafusion_expr::ScalarUDF;
4279        use datafusion_functions::math::abs::AbsFunc;
4280        use datafusion_physical_expr::ScalarFunctionExpr;
4281
4282        Arc::new(ScalarFunctionExpr::new(
4283            "abs",
4284            Arc::new(ScalarUDF::from(AbsFunc::new())),
4285            args,
4286            Arc::new(Field::new("abs", DataType::Int32, false)),
4287            Arc::new(ConfigOptions::default()),
4288        ))
4289    }
4290
4291    /// Helper: create a cheap, leaf-pushable scalar function — struct field
4292    /// access `get_field(s, 'x')`, whose placement is `MoveTowardsLeafNodes`
4293    /// when the base is a column and the key is a literal.
4294    fn make_leaf_pushable_expr() -> Arc<dyn PhysicalExpr> {
4295        use datafusion_common::config::ConfigOptions;
4296        use datafusion_expr::ScalarUDF;
4297        use datafusion_functions::core::getfield::GetFieldFunc;
4298        use datafusion_physical_expr::ScalarFunctionExpr;
4299        use datafusion_physical_expr::expressions::Literal;
4300
4301        Arc::new(ScalarFunctionExpr::new(
4302            "get_field",
4303            Arc::new(ScalarUDF::from(GetFieldFunc::new())),
4304            vec![
4305                Arc::new(Column::new("s", 0)),
4306                Arc::new(Literal::new(ScalarValue::Utf8(Some("x".to_string())))),
4307            ],
4308            Arc::new(Field::new("x", DataType::Int32, true)),
4309            Arc::new(ConfigOptions::default()),
4310        ))
4311    }
4312
4313    /// Column-only inner projections always merge safely, even when
4314    /// the outer projection references them multiple times.
4315    #[test]
4316    fn test_would_duplicate_allows_column_only_inner() {
4317        let col_a: Arc<dyn PhysicalExpr> = Arc::new(Column::new("a", 0));
4318        let col_b: Arc<dyn PhysicalExpr> = Arc::new(Column::new("b", 1));
4319
4320        let inner =
4321            make_projection(vec![(Arc::clone(&col_a), "a"), (Arc::clone(&col_b), "b")]);
4322
4323        // Outer references col 0 twice
4324        let outer = make_projection(vec![
4325            (Arc::new(Column::new("a", 0)), "x"),
4326            (Arc::new(Column::new("a", 0)), "y"),
4327        ]);
4328
4329        assert!(!would_duplicate_costly_exprs(&inner, &outer));
4330    }
4331
4332    /// A non-trivial computed expression (arithmetic, `KeepInPlace`) referenced
4333    /// multiple times blocks the merge — recomputing it per site is wasteful.
4334    #[test]
4335    fn test_would_duplicate_blocks_computed_multi_ref() {
4336        let col_a: Arc<dyn PhysicalExpr> = Arc::new(Column::new("a", 0));
4337        let col_b: Arc<dyn PhysicalExpr> = Arc::new(Column::new("b", 1));
4338        // Inner: [a + b, b]  (index 0 is a non-trivial computed expression)
4339        let inner = make_projection(vec![
4340            (
4341                Arc::new(BinaryExpr::new(
4342                    Arc::clone(&col_a),
4343                    Operator::Plus,
4344                    Arc::clone(&col_b),
4345                )),
4346                "sum",
4347            ),
4348            (Arc::clone(&col_b), "b"),
4349        ]);
4350
4351        // Outer references index 0 twice
4352        let outer = make_projection(vec![
4353            (Arc::new(Column::new("sum", 0)), "x"),
4354            (Arc::new(Column::new("sum", 0)), "y"),
4355        ]);
4356
4357        assert!(would_duplicate_costly_exprs(&inner, &outer));
4358    }
4359
4360    /// A volatile expression the outer projection does not reference is
4361    /// safe to merge (it is projected away, not duplicated).
4362    #[test]
4363    fn test_would_duplicate_allows_unreferenced_volatile() {
4364        let col_a: Arc<dyn PhysicalExpr> = Arc::new(Column::new("a", 0));
4365        // Inner: [random(), a]
4366        let inner =
4367            make_projection(vec![(make_volatile_expr(), "r"), (Arc::clone(&col_a), "a")]);
4368
4369        // Outer references only index 1 (the column), not the volatile expr
4370        let outer = make_projection(vec![(Arc::new(Column::new("a", 1)), "a")]);
4371
4372        assert!(!would_duplicate_costly_exprs(&inner, &outer));
4373    }
4374
4375    /// A volatile expression referenced multiple times must block merge:
4376    /// this is the #23220 regression (`random()` aliased then referenced as
4377    /// `x` and `y`).
4378    #[test]
4379    fn test_would_duplicate_blocks_multi_ref_volatile() {
4380        // Inner: [random()]
4381        let inner = make_projection(vec![(make_volatile_expr(), "r")]);
4382
4383        // Outer references index 0 twice
4384        let outer = make_projection(vec![
4385            (Arc::new(Column::new("r", 0)), "x"),
4386            (Arc::new(Column::new("r", 0)), "y"),
4387        ]);
4388
4389        assert!(would_duplicate_costly_exprs(&inner, &outer));
4390    }
4391
4392    /// A volatile expression referenced exactly once has nothing to duplicate,
4393    /// so the merge is allowed.
4394    #[test]
4395    fn test_would_duplicate_allows_single_ref_volatile() {
4396        let col_a: Arc<dyn PhysicalExpr> = Arc::new(Column::new("a", 0));
4397        // Inner: [random(), a]
4398        let inner =
4399            make_projection(vec![(make_volatile_expr(), "r"), (Arc::clone(&col_a), "a")]);
4400
4401        // Outer references the volatile expression exactly once
4402        let outer = make_projection(vec![
4403            (Arc::new(Column::new("r", 0)), "x"),
4404            (Arc::new(Column::new("a", 1)), "a"),
4405        ]);
4406
4407        assert!(!would_duplicate_costly_exprs(&inner, &outer));
4408    }
4409
4410    /// References are counted with multiplicity, so a single outer expression
4411    /// that duplicates the value (e.g. `r + r`) still blocks the merge.
4412    #[test]
4413    fn test_would_duplicate_blocks_single_expr_self_ref_volatile() {
4414        // Inner: [random()]
4415        let inner = make_projection(vec![(make_volatile_expr(), "r")]);
4416
4417        // Outer: [r + r] — one expression referencing `random()` twice
4418        let outer = make_projection(vec![(
4419            Arc::new(BinaryExpr::new(
4420                Arc::new(Column::new("r", 0)),
4421                Operator::Plus,
4422                Arc::new(Column::new("r", 0)),
4423            )),
4424            "x",
4425        )]);
4426
4427        assert!(would_duplicate_costly_exprs(&inner, &outer));
4428    }
4429
4430    /// A volatile expression buried inside a larger expression (e.g.
4431    /// `random() + 1`) is still detected and blocks merge.
4432    #[test]
4433    fn test_would_duplicate_blocks_volatile_nested_in_arithmetic() {
4434        // Inner: [random() + 1]
4435        let inner = make_projection(vec![(
4436            Arc::new(BinaryExpr::new(
4437                make_volatile_expr(),
4438                Operator::Plus,
4439                Arc::new(Literal::new(ScalarValue::Float64(Some(1.0)))),
4440            )),
4441            "expr",
4442        )]);
4443
4444        // Outer references index 0 twice
4445        let outer = make_projection(vec![
4446            (Arc::new(Column::new("expr", 0)), "x"),
4447            (Arc::new(Column::new("expr", 0)), "y"),
4448        ]);
4449
4450        assert!(would_duplicate_costly_exprs(&inner, &outer));
4451    }
4452
4453    /// Empty projections should not block merging.
4454    #[test]
4455    fn test_would_duplicate_empty_projections() {
4456        let inner = make_projection(vec![]);
4457        let outer = make_projection(vec![]);
4458        assert!(!would_duplicate_costly_exprs(&inner, &outer));
4459    }
4460
4461    /// An expensive (scalar-function) expression referenced more than once
4462    /// must block the merge to preserve CSE.
4463    #[test]
4464    fn test_would_duplicate_blocks_multi_ref_expensive() {
4465        let col_a: Arc<dyn PhysicalExpr> = Arc::new(Column::new("a", 0));
4466        // Inner: [abs(a)]
4467        let inner = make_projection(vec![(make_udf_expr(vec![col_a]), "abs_a")]);
4468
4469        // Outer references index 0 twice
4470        let outer = make_projection(vec![
4471            (Arc::new(Column::new("abs_a", 0)), "x"),
4472            (Arc::new(Column::new("abs_a", 0)), "y"),
4473        ]);
4474
4475        assert!(would_duplicate_costly_exprs(&inner, &outer));
4476    }
4477
4478    /// An expensive expression referenced only once has nothing to duplicate,
4479    /// so the merge is allowed.
4480    #[test]
4481    fn test_would_duplicate_allows_single_ref_expensive() {
4482        let col_a: Arc<dyn PhysicalExpr> = Arc::new(Column::new("a", 0));
4483        // Inner: [abs(a), a]
4484        let inner = make_projection(vec![
4485            (make_udf_expr(vec![Arc::clone(&col_a)]), "abs_a"),
4486            (Arc::clone(&col_a), "a"),
4487        ]);
4488
4489        // Outer references each inner column once
4490        let outer = make_projection(vec![
4491            (Arc::new(Column::new("abs_a", 0)), "out"),
4492            (Arc::new(Column::new("a", 1)), "a"),
4493        ]);
4494
4495        assert!(!would_duplicate_costly_exprs(&inner, &outer));
4496    }
4497
4498    /// A cheap, leaf-pushable scalar function (placement
4499    /// `MoveTowardsLeafNodes`, e.g. `get_field` / `input_file_name`) still
4500    /// merges even when referenced multiple times — it is meant to be pushed
4501    /// into the scan, so blocking would defeat that optimization.
4502    #[test]
4503    fn test_would_duplicate_allows_leaf_pushable_scalar_function() {
4504        // Inner: [input_file_name()]
4505        let inner = make_projection(vec![(make_leaf_pushable_expr(), "f")]);
4506
4507        // Outer references index 0 twice
4508        let outer = make_projection(vec![
4509            (Arc::new(Column::new("f", 0)), "x"),
4510            (Arc::new(Column::new("f", 0)), "y"),
4511        ]);
4512
4513        assert!(!would_duplicate_costly_exprs(&inner, &outer));
4514    }
4515}