Skip to main content

datafusion_datasource/
memory.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
5use std::cmp::Ordering;
6use std::collections::BinaryHeap;
7use std::fmt;
8use std::fmt::Debug;
9use std::ops::Deref;
10use std::slice::from_ref;
11use std::sync::Arc;
12
13use crate::sink::DataSink;
14use crate::source::{DataSource, DataSourceExec};
15
16use arrow::array::{RecordBatch, RecordBatchOptions};
17use arrow::datatypes::{Schema, SchemaRef};
18use datafusion_common::tree_node::TreeNodeRecursion;
19use datafusion_common::{
20    Result, ScalarValue, assert_or_internal_err, plan_err, project_schema,
21};
22use datafusion_execution::TaskContext;
23use datafusion_physical_expr::equivalence::project_orderings;
24use datafusion_physical_expr::projection::ProjectionExprs;
25use datafusion_physical_expr::utils::collect_columns;
26use datafusion_physical_expr::{EquivalenceProperties, LexOrdering};
27use datafusion_physical_plan::memory::MemoryStream;
28use datafusion_physical_plan::projection::{
29    all_alias_free_columns, new_projections_for_columns,
30};
31use datafusion_physical_plan::{
32    ColumnarValue, DisplayAs, DisplayFormatType, Partitioning, PhysicalExpr,
33    SendableRecordBatchStream, Statistics, common,
34};
35
36use async_trait::async_trait;
37use datafusion_physical_plan::coop::cooperative;
38use datafusion_physical_plan::execution_plan::SchedulingType;
39use futures::StreamExt;
40use itertools::Itertools;
41use tokio::sync::RwLock;
42
43/// Data source configuration for reading in-memory batches of data
44#[derive(Clone, Debug)]
45pub struct MemorySourceConfig {
46    /// The partitions to query.
47    ///
48    /// Each partition is a `Vec<RecordBatch>`.
49    partitions: Vec<Vec<RecordBatch>>,
50    /// Schema representing the data before projection
51    schema: SchemaRef,
52    /// Schema representing the data after the optional projection is applied
53    projected_schema: SchemaRef,
54    /// Optional projection
55    projection: Option<Vec<usize>>,
56    /// Sort information: one or more equivalent orderings
57    sort_information: Vec<LexOrdering>,
58    /// if partition sizes should be displayed
59    show_sizes: bool,
60    /// The maximum number of records to read from this plan. If `None`,
61    /// all records after filtering are returned.
62    fetch: Option<usize>,
63}
64
65impl DataSource for MemorySourceConfig {
66    fn open(
67        &self,
68        partition: usize,
69        _context: Arc<TaskContext>,
70    ) -> Result<SendableRecordBatchStream> {
71        Ok(Box::pin(cooperative(
72            MemoryStream::try_new(
73                self.partitions[partition].clone(),
74                Arc::clone(&self.projected_schema),
75                self.projection.clone(),
76            )?
77            .with_fetch(self.fetch),
78        )))
79    }
80
81    fn fmt_as(&self, t: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result {
82        match t {
83            DisplayFormatType::Default | DisplayFormatType::Verbose => {
84                let partition_sizes: Vec<_> =
85                    self.partitions.iter().map(|b| b.len()).collect();
86
87                let output_ordering = self
88                    .sort_information
89                    .first()
90                    .map(|output_ordering| format!(", output_ordering={output_ordering}"))
91                    .unwrap_or_default();
92
93                let eq_properties = self.eq_properties();
94                let constraints = eq_properties.constraints();
95                let constraints = if constraints.is_empty() {
96                    String::new()
97                } else {
98                    format!(", {constraints}")
99                };
100
101                let limit = self
102                    .fetch
103                    .map_or(String::new(), |limit| format!(", fetch={limit}"));
104                if self.show_sizes {
105                    write!(
106                        f,
107                        "partitions={}, partition_sizes={partition_sizes:?}{limit}{output_ordering}{constraints}",
108                        partition_sizes.len(),
109                    )
110                } else {
111                    write!(
112                        f,
113                        "partitions={}{limit}{output_ordering}{constraints}",
114                        partition_sizes.len(),
115                    )
116                }
117            }
118            DisplayFormatType::TreeRender => {
119                let total_rows = self
120                    .partitions
121                    .iter()
122                    .flatten()
123                    .map(RecordBatch::num_rows)
124                    .sum::<usize>();
125                let total_bytes: usize = self
126                    .partitions
127                    .iter()
128                    .flatten()
129                    .map(|batch| batch.get_array_memory_size())
130                    .sum();
131                writeln!(f, "format=memory")?;
132                writeln!(f, "rows={total_rows}")?;
133                writeln!(f, "bytes={total_bytes}")?;
134                Ok(())
135            }
136        }
137    }
138
139    /// If possible, redistribute batches across partitions according to their size.
140    ///
141    /// Returns `Ok(None)` if unable to repartition. Preserve output ordering if exists.
142    /// Refer to [`DataSource::repartitioned`] for further details.
143    fn repartitioned(
144        &self,
145        target_partitions: usize,
146        _repartition_file_min_size: usize,
147        output_ordering: Option<LexOrdering>,
148    ) -> Result<Option<Arc<dyn DataSource>>> {
149        if self.partitions.is_empty() || self.partitions.len() >= target_partitions
150        // if have no partitions, or already have more partitions than desired, do not repartition
151        {
152            return Ok(None);
153        }
154
155        let maybe_repartitioned = if let Some(output_ordering) = output_ordering {
156            self.repartition_preserving_order(target_partitions, output_ordering)?
157        } else {
158            self.repartition_evenly_by_size(target_partitions)?
159        };
160
161        if let Some(repartitioned) = maybe_repartitioned {
162            Ok(Some(Arc::new(Self::try_new(
163                &repartitioned,
164                self.original_schema(),
165                self.projection.clone(),
166            )?)))
167        } else {
168            Ok(None)
169        }
170    }
171
172    fn output_partitioning(&self) -> Partitioning {
173        Partitioning::UnknownPartitioning(self.partitions.len())
174    }
175
176    fn eq_properties(&self) -> EquivalenceProperties {
177        EquivalenceProperties::new_with_orderings(
178            Arc::clone(&self.projected_schema),
179            self.sort_information.clone(),
180        )
181    }
182
183    fn scheduling_type(&self) -> SchedulingType {
184        SchedulingType::Cooperative
185    }
186
187    fn partition_statistics(&self, partition: Option<usize>) -> Result<Arc<Statistics>> {
188        if let Some(partition) = partition {
189            // Compute statistics for a specific partition
190            if let Some(batches) = self.partitions.get(partition) {
191                Ok(Arc::new(common::compute_record_batch_statistics(
192                    from_ref(batches),
193                    &self.schema,
194                    self.projection.clone(),
195                )))
196            } else {
197                // Invalid partition index
198                Ok(Arc::new(Statistics::new_unknown(&self.projected_schema)))
199            }
200        } else {
201            // Compute statistics across all partitions
202            Ok(Arc::new(common::compute_record_batch_statistics(
203                &self.partitions,
204                &self.schema,
205                self.projection.clone(),
206            )))
207        }
208    }
209
210    fn with_fetch(&self, limit: Option<usize>) -> Option<Arc<dyn DataSource>> {
211        let source = self.clone();
212        Some(Arc::new(source.with_limit(limit)))
213    }
214
215    fn fetch(&self) -> Option<usize> {
216        self.fetch
217    }
218
219    fn try_swapping_with_projection(
220        &self,
221        projection: &ProjectionExprs,
222    ) -> Result<Option<Arc<dyn DataSource>>> {
223        // If there is any non-column or alias-carrier expression, Projection should not be removed.
224        // This process can be moved into MemoryExec, but it would be an overlap of their responsibility.
225        let exprs = projection.iter().cloned().collect_vec();
226        all_alias_free_columns(exprs.as_slice())
227            .then(|| {
228                let all_projections = (0..self.schema.fields().len()).collect();
229                let new_projections = new_projections_for_columns(
230                    &exprs,
231                    self.projection().as_ref().unwrap_or(&all_projections),
232                );
233                let projected_schema =
234                    project_schema(&self.schema, Some(&new_projections));
235
236                projected_schema.map(|projected_schema| {
237                    // Clone self to preserve all metadata (fetch, sort_information,
238                    // show_sizes, etc.) then update only the projection-related fields.
239                    let mut new_source = self.clone();
240                    new_source.projection = Some(new_projections);
241                    new_source.projected_schema = projected_schema;
242                    // Project sort information to match the new projection
243                    new_source.sort_information = project_orderings(
244                        &new_source.sort_information,
245                        &new_source.projected_schema,
246                    );
247                    Arc::new(new_source) as Arc<dyn DataSource>
248                })
249            })
250            .transpose()
251    }
252
253    fn apply_expressions(
254        &self,
255        _f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
256    ) -> Result<TreeNodeRecursion> {
257        Ok(TreeNodeRecursion::Continue)
258    }
259
260    /// Serialize this `MemorySourceConfig` as a `MemoryScanExecNode` wrapped
261    /// in a [`PhysicalPlanNode`]. Byte-compatible with the former central
262    /// `MemoryScan` arm in `datafusion-proto`.
263    ///
264    /// [`PhysicalPlanNode`]: datafusion_proto_models::protobuf::PhysicalPlanNode
265    #[cfg(feature = "proto")]
266    fn try_to_proto(
267        &self,
268        ctx: &datafusion_physical_plan::proto::ExecutionPlanEncodeCtx<'_>,
269    ) -> Result<Option<datafusion_proto_models::protobuf::PhysicalPlanNode>> {
270        use datafusion_common::utils::usize_to_wire;
271        use datafusion_physical_expr_common::sort_expr::sort_exprs_try_to_proto;
272        use datafusion_proto_models::protobuf;
273
274        // Exhaustive destructure: adding a field to `MemorySourceConfig`
275        // without deciding how it is serialized is a compile error, not a
276        // silent round-trip gap.
277        let Self {
278            partitions: source_partitions,
279            schema,
280            // Derived from `schema` and `projection` by `try_new` on decode.
281            projected_schema: _,
282            projection: source_projection,
283            sort_information,
284            show_sizes,
285            fetch,
286        } = self;
287
288        let proto_partitions = source_partitions
289            .iter()
290            .map(|batches| record_batches_to_ipc_bytes(batches))
291            .collect::<Result<Vec<_>>>()?;
292
293        // Proto3 can't tell `None` from `Some(vec![])`; encode the latter
294        // as the `[u32::MAX]` sentinel, matching the join/filter nodes.
295        let proto_projection = match source_projection.as_ref() {
296            None => Vec::new(),
297            Some(v) if v.is_empty() => vec![u32::MAX],
298            Some(v) => v.iter().map(|x| *x as u32).collect(),
299        };
300
301        let mut proto_sort_information = Vec::with_capacity(sort_information.len());
302        for ordering in sort_information {
303            let physical_sort_expr_nodes =
304                sort_exprs_try_to_proto(ordering.iter(), &ctx.expr_ctx())?;
305            proto_sort_information.push(protobuf::PhysicalSortExprNodeCollection {
306                physical_sort_expr_nodes,
307            });
308        }
309
310        Ok(Some(protobuf::PhysicalPlanNode {
311            physical_plan_type: Some(
312                protobuf::physical_plan_node::PhysicalPlanType::MemoryScan(
313                    protobuf::MemoryScanExecNode {
314                        partitions: proto_partitions,
315                        schema: Some(schema.as_ref().try_into()?),
316                        projection: proto_projection,
317                        sort_information: proto_sort_information,
318                        show_sizes: *show_sizes,
319                        fetch: fetch
320                            .map(|fetch| {
321                                usize_to_wire(fetch, "MemoryScanExecNode", "fetch")
322                            })
323                            .transpose()?,
324                    },
325                ),
326            ),
327        }))
328    }
329}
330
331impl MemorySourceConfig {
332    /// Create a new `MemorySourceConfig` for reading in-memory record batches
333    /// The provided `schema` should not have the projection applied.
334    pub fn try_new(
335        partitions: &[Vec<RecordBatch>],
336        schema: SchemaRef,
337        projection: Option<Vec<usize>>,
338    ) -> Result<Self> {
339        let projected_schema = project_schema(&schema, projection.as_ref())?;
340        Ok(Self {
341            partitions: partitions.to_vec(),
342            schema,
343            projected_schema,
344            projection,
345            sort_information: vec![],
346            show_sizes: true,
347            fetch: None,
348        })
349    }
350
351    /// Create a new `DataSourceExec` plan for reading in-memory record batches
352    /// The provided `schema` should not have the projection applied.
353    pub fn try_new_exec(
354        partitions: &[Vec<RecordBatch>],
355        schema: SchemaRef,
356        projection: Option<Vec<usize>>,
357    ) -> Result<Arc<DataSourceExec>> {
358        let source = Self::try_new(partitions, schema, projection)?;
359        Ok(DataSourceExec::from_data_source(source))
360    }
361
362    /// Create a new execution plan from a list of constant values (`ValuesExec`)
363    #[expect(clippy::needless_pass_by_value)]
364    pub fn try_new_as_values(
365        schema: SchemaRef,
366        data: Vec<Vec<Arc<dyn PhysicalExpr>>>,
367    ) -> Result<Arc<DataSourceExec>> {
368        if data.is_empty() {
369            return plan_err!("Values list cannot be empty");
370        }
371
372        let n_row = data.len();
373        let n_col = schema.fields().len();
374
375        // We have this single row batch as a placeholder to satisfy evaluation argument
376        // and generate a single output row
377        let placeholder_schema = Arc::new(Schema::empty());
378        let placeholder_batch = RecordBatch::try_new_with_options(
379            Arc::clone(&placeholder_schema),
380            vec![],
381            &RecordBatchOptions::new().with_row_count(Some(1)),
382        )?;
383
384        // Evaluate each column
385        let arrays = (0..n_col)
386            .map(|j| {
387                (0..n_row)
388                    .map(|i| {
389                        let expr = &data[i][j];
390                        let result = expr.evaluate(&placeholder_batch)?;
391
392                        match result {
393                            ColumnarValue::Scalar(scalar) => Ok(scalar),
394                            ColumnarValue::Array(array) if array.len() == 1 => {
395                                ScalarValue::try_from_array(&array, 0)
396                            }
397                            ColumnarValue::Array(_) => {
398                                plan_err!("Cannot have array values in a values list")
399                            }
400                        }
401                    })
402                    .collect::<Result<Vec<_>>>()
403                    .and_then(ScalarValue::iter_to_array)
404            })
405            .collect::<Result<Vec<_>>>()?;
406
407        let batch = RecordBatch::try_new_with_options(
408            Arc::clone(&schema),
409            arrays,
410            &RecordBatchOptions::new().with_row_count(Some(n_row)),
411        )?;
412
413        let partitions = vec![batch];
414        Self::try_new_from_batches(Arc::clone(&schema), partitions)
415    }
416
417    /// Create a new plan using the provided schema and batches.
418    ///
419    /// Errors if any of the batches don't match the provided schema, or if no
420    /// batches are provided.
421    #[expect(clippy::needless_pass_by_value)]
422    pub fn try_new_from_batches(
423        schema: SchemaRef,
424        batches: Vec<RecordBatch>,
425    ) -> Result<Arc<DataSourceExec>> {
426        if batches.is_empty() {
427            return plan_err!("Values list cannot be empty");
428        }
429
430        for batch in &batches {
431            let batch_schema = batch.schema();
432            if batch_schema != schema {
433                return plan_err!(
434                    "Batch has invalid schema. Expected: {}, got: {}",
435                    schema,
436                    batch_schema
437                );
438            }
439        }
440
441        let partitions = vec![batches];
442        let source = Self {
443            partitions,
444            schema: Arc::clone(&schema),
445            projected_schema: Arc::clone(&schema),
446            projection: None,
447            sort_information: vec![],
448            show_sizes: true,
449            fetch: None,
450        };
451        Ok(DataSourceExec::from_data_source(source))
452    }
453
454    /// Set the limit of the files
455    pub fn with_limit(mut self, limit: Option<usize>) -> Self {
456        self.fetch = limit;
457        self
458    }
459
460    /// Set `show_sizes` to determine whether to display partition sizes
461    pub fn with_show_sizes(mut self, show_sizes: bool) -> Self {
462        self.show_sizes = show_sizes;
463        self
464    }
465
466    /// Ref to partitions
467    pub fn partitions(&self) -> &[Vec<RecordBatch>] {
468        &self.partitions
469    }
470
471    /// Ref to projection
472    pub fn projection(&self) -> &Option<Vec<usize>> {
473        &self.projection
474    }
475
476    /// Show sizes
477    pub fn show_sizes(&self) -> bool {
478        self.show_sizes
479    }
480
481    /// Ref to sort information
482    pub fn sort_information(&self) -> &[LexOrdering] {
483        &self.sort_information
484    }
485
486    /// A memory table can be ordered by multiple expressions simultaneously.
487    /// [`EquivalenceProperties`] keeps track of expressions that describe the
488    /// global ordering of the schema. These columns are not necessarily same; e.g.
489    /// ```text
490    /// ┌-------┐
491    /// | a | b |
492    /// |---|---|
493    /// | 1 | 9 |
494    /// | 2 | 8 |
495    /// | 3 | 7 |
496    /// | 5 | 5 |
497    /// └---┴---┘
498    /// ```
499    /// where both `a ASC` and `b DESC` can describe the table ordering. With
500    /// [`EquivalenceProperties`], we can keep track of these equivalences
501    /// and treat `a ASC` and `b DESC` as the same ordering requirement.
502    ///
503    /// Note that if there is an internal projection, that projection will be
504    /// also applied to the given `sort_information`.
505    pub fn try_with_sort_information(
506        mut self,
507        mut sort_information: Vec<LexOrdering>,
508    ) -> Result<Self> {
509        // All sort expressions must refer to the original schema.
510        Self::validate_sort_information(&sort_information, &self.schema, "original")?;
511
512        // If there is a projection on the source, we also need to project orderings
513        if self.projection.is_some() {
514            sort_information =
515                project_orderings(&sort_information, &self.projected_schema);
516        }
517
518        self.sort_information = sort_information;
519        Ok(self)
520    }
521
522    fn validate_sort_information(
523        sort_information: &[LexOrdering],
524        schema: &Schema,
525        schema_name: &str,
526    ) -> Result<()> {
527        let fields = schema.fields();
528        let ambiguous_column = sort_information
529            .iter()
530            .flat_map(|ordering| ordering.iter())
531            .flat_map(|expr| collect_columns(&expr.expr))
532            .find(|col| {
533                fields
534                    .get(col.index())
535                    .map(|field| field.name() != col.name())
536                    .unwrap_or(true)
537            });
538        assert_or_internal_err!(
539            ambiguous_column.is_none(),
540            "Column {:?} is not found in the {schema_name} schema of the MemorySourceConfig",
541            ambiguous_column.as_ref().unwrap()
542        );
543        Ok(())
544    }
545
546    /// Arc clone of ref to original schema
547    pub fn original_schema(&self) -> SchemaRef {
548        Arc::clone(&self.schema)
549    }
550
551    /// Repartition while preserving order.
552    ///
553    /// Returns `Ok(None)` if cannot fulfill the requested repartitioning, such
554    /// as having too few batches to fulfill the `target_partitions` or if unable
555    /// to preserve output ordering.
556    fn repartition_preserving_order(
557        &self,
558        target_partitions: usize,
559        output_ordering: LexOrdering,
560    ) -> Result<Option<Vec<Vec<RecordBatch>>>> {
561        if !self.eq_properties().ordering_satisfy(output_ordering)? {
562            Ok(None)
563        } else {
564            let total_num_batches =
565                self.partitions.iter().map(|b| b.len()).sum::<usize>();
566            if total_num_batches < target_partitions {
567                // no way to create the desired repartitioning
568                return Ok(None);
569            }
570
571            let cnt_to_repartition = target_partitions - self.partitions.len();
572
573            // Label the current partitions and their order.
574            // Such that when we later split up the partitions into smaller sizes, we are maintaining the order.
575            let to_repartition = self
576                .partitions
577                .iter()
578                .enumerate()
579                .map(|(idx, batches)| RePartition {
580                    idx: idx + (cnt_to_repartition * idx), // make space in ordering for split partitions
581                    row_count: batches.iter().map(|batch| batch.num_rows()).sum(),
582                    batches: batches.clone(),
583                })
584                .collect_vec();
585
586            // Put all of the partitions into a heap ordered by `RePartition::partial_cmp`, which sizes
587            // by count of rows.
588            let mut max_heap = BinaryHeap::with_capacity(target_partitions);
589            for rep in to_repartition {
590                max_heap.push(CompareByRowCount(rep));
591            }
592
593            // Split the largest partitions into smaller partitions. Maintaining the output
594            // order of the partitions & newly created partitions.
595            let mut cannot_split_further = Vec::with_capacity(target_partitions);
596            for _ in 0..cnt_to_repartition {
597                // triggers loop for the cnt_to_repartition. So if need another 4 partitions, it attempts to split 4 times.
598                loop {
599                    // Take the largest item off the heap, and attempt to split.
600                    let Some(to_split) = max_heap.pop() else {
601                        // Nothing left to attempt repartition. Break inner loop.
602                        break;
603                    };
604
605                    // Split the partition. The new partitions will be ordered with idx and idx+1.
606                    let mut new_partitions = to_split.into_inner().split();
607                    if new_partitions.len() > 1 {
608                        for new_partition in new_partitions {
609                            max_heap.push(CompareByRowCount(new_partition));
610                        }
611                        // Successful repartition. Break inner loop, and return to outer `cnt_to_repartition` loop.
612                        break;
613                    } else {
614                        cannot_split_further.push(new_partitions.remove(0));
615                    }
616                }
617            }
618            let mut partitions = max_heap
619                .drain()
620                .map(CompareByRowCount::into_inner)
621                .collect_vec();
622            partitions.extend(cannot_split_further);
623
624            // Finally, sort all partitions by the output ordering.
625            // This was the original ordering of the batches within the partition. We are maintaining this ordering.
626            partitions.sort_by_key(|p| p.idx);
627            let partitions = partitions.into_iter().map(|rep| rep.batches).collect_vec();
628
629            Ok(Some(partitions))
630        }
631    }
632
633    /// Repartition into evenly sized chunks (as much as possible without batch splitting),
634    /// disregarding any ordering.
635    ///
636    /// Current implementation uses a first-fit-decreasing bin packing, modified to enable
637    /// us to still return the desired count of `target_partitions`.
638    ///
639    /// Returns `Ok(None)` if cannot fulfill the requested repartitioning, such
640    /// as having too few batches to fulfill the `target_partitions`.
641    fn repartition_evenly_by_size(
642        &self,
643        target_partitions: usize,
644    ) -> Result<Option<Vec<Vec<RecordBatch>>>> {
645        // determine if we have enough total batches to fulfill request
646        let mut flatten_batches =
647            self.partitions.clone().into_iter().flatten().collect_vec();
648        if flatten_batches.len() < target_partitions {
649            return Ok(None);
650        }
651
652        // Take all flattened batches (all in 1 partititon/vec) and divide evenly into the desired number of `target_partitions`.
653        let total_num_rows = flatten_batches.iter().map(|b| b.num_rows()).sum::<usize>();
654        // sort by size, so we pack multiple smaller batches into the same partition
655        flatten_batches.sort_by_key(|b| std::cmp::Reverse(b.num_rows()));
656
657        // Divide.
658        let mut partitions =
659            vec![Vec::with_capacity(flatten_batches.len()); target_partitions];
660        let mut target_partition_size = total_num_rows.div_ceil(target_partitions);
661        let mut total_rows_seen = 0;
662        let mut curr_bin_row_count = 0;
663        let mut idx = 0;
664        for batch in flatten_batches {
665            let row_cnt = batch.num_rows();
666            idx = std::cmp::min(idx, target_partitions - 1);
667
668            partitions[idx].push(batch);
669            curr_bin_row_count += row_cnt;
670            total_rows_seen += row_cnt;
671
672            if curr_bin_row_count >= target_partition_size {
673                idx += 1;
674                curr_bin_row_count = 0;
675
676                // update target_partition_size, to handle very lopsided batch distributions
677                // while still returning the count of `target_partitions`
678                if total_rows_seen < total_num_rows {
679                    target_partition_size = (total_num_rows - total_rows_seen)
680                        .div_ceil(target_partitions - idx);
681                }
682            }
683        }
684
685        Ok(Some(partitions))
686    }
687}
688
689#[cfg(feature = "proto")]
690impl MemorySourceConfig {
691    /// Reconstruct a [`DataSourceExec`] wrapping a `MemorySourceConfig` from
692    /// its protobuf representation. Byte-compatible with the former central
693    /// `MemoryScan` arm in `datafusion-proto`.
694    pub fn try_from_proto(
695        node: &datafusion_proto_models::protobuf::PhysicalPlanNode,
696        ctx: &datafusion_physical_plan::proto::ExecutionPlanDecodeCtx<'_>,
697    ) -> Result<Arc<dyn datafusion_physical_plan::ExecutionPlan>> {
698        use datafusion_common::internal_datafusion_err;
699        use datafusion_common::utils::usize_from_wire;
700        use datafusion_physical_expr_common::sort_expr::optional_ordering_try_from_proto;
701        use datafusion_proto_models::protobuf;
702
703        let scan = datafusion_physical_plan::expect_plan_variant!(
704            node,
705            protobuf::physical_plan_node::PhysicalPlanType::MemoryScan,
706            "MemorySourceConfig",
707        );
708
709        // Destructure exhaustively so a newly added protobuf field must be
710        // handled here instead of being silently ignored.
711        let protobuf::MemoryScanExecNode {
712            partitions: proto_partitions,
713            schema: encoded_schema,
714            projection: proto_projection,
715            sort_information: proto_sort_information,
716            show_sizes,
717            fetch: proto_fetch,
718        } = scan;
719
720        let partitions = proto_partitions
721            .iter()
722            .map(|buf| record_batches_from_ipc_bytes(buf))
723            .collect::<Result<Vec<_>>>()?;
724
725        let proto_schema = encoded_schema.as_ref().ok_or_else(|| {
726            internal_datafusion_err!("schema in MemoryScanExecNode is missing.")
727        })?;
728        let source_schema: SchemaRef = SchemaRef::new(proto_schema.try_into()?);
729
730        // Preserve the empty-projection sentinel written by `try_to_proto`.
731        let projection = match proto_projection.as_slice() {
732            [] => None,
733            [u32::MAX] => Some(Vec::new()),
734            indices => Some(indices.iter().map(|i| *i as usize).collect()),
735        };
736        let fetch = proto_fetch
737            .map(|fetch| usize_from_wire(fetch, "MemoryScanExecNode", "fetch"))
738            .transpose()?;
739        let mut source = Self::try_new(&partitions, source_schema, projection)?
740            .with_limit(fetch)
741            .with_show_sizes(*show_sizes);
742
743        // Stored sort information has already been projected by
744        // `try_with_sort_information`; decode it against that same schema and
745        // do not project it a second time.
746        let mut decoded_sort_information =
747            Vec::with_capacity(proto_sort_information.len());
748        for ordering in proto_sort_information {
749            let protobuf::PhysicalSortExprNodeCollection {
750                physical_sort_expr_nodes,
751            } = ordering;
752            if let Some(ordering) = optional_ordering_try_from_proto(
753                physical_sort_expr_nodes,
754                &ctx.expr_ctx(&source.projected_schema),
755            )? {
756                decoded_sort_information.push(ordering);
757            }
758        }
759        Self::validate_sort_information(
760            &decoded_sort_information,
761            &source.projected_schema,
762            "projected",
763        )?;
764        source.sort_information = decoded_sort_information;
765
766        Ok(DataSourceExec::from_data_source(source))
767    }
768}
769
770/// Encode record batches as Arrow IPC stream bytes; an empty slice encodes to
771/// an empty buffer.
772#[cfg(feature = "proto")]
773fn record_batches_to_ipc_bytes(batches: &[RecordBatch]) -> Result<Vec<u8>> {
774    use arrow::ipc::writer::StreamWriter;
775
776    if batches.is_empty() {
777        return Ok(vec![]);
778    }
779    let schema = batches[0].schema();
780    let mut buf = Vec::new();
781    let mut writer = StreamWriter::try_new(&mut buf, &schema)?;
782    for batch in batches {
783        writer.write(batch)?;
784    }
785    writer.finish()?;
786    Ok(buf)
787}
788
789/// Inverse of [`record_batches_to_ipc_bytes`].
790#[cfg(feature = "proto")]
791fn record_batches_from_ipc_bytes(buf: &[u8]) -> Result<Vec<RecordBatch>> {
792    use arrow::ipc::reader::StreamReader;
793
794    if buf.is_empty() {
795        return Ok(vec![]);
796    }
797    let reader = StreamReader::try_new(buf, None)?;
798    let mut batches = Vec::new();
799    for batch in reader {
800        batches.push(batch?);
801    }
802    Ok(batches)
803}
804
805/// For use in repartitioning, track the total size and original partition index.
806///
807/// Do not implement clone, in order to avoid unnecessary copying during repartitioning.
808struct RePartition {
809    /// Original output ordering for the partition.
810    idx: usize,
811    /// Total size of the partition, for use in heap ordering
812    /// (a.k.a. splitting up the largest partitions).
813    row_count: usize,
814    /// A partition containing record batches.
815    batches: Vec<RecordBatch>,
816}
817
818impl RePartition {
819    /// Split [`RePartition`] into 2 pieces, consuming self.
820    ///
821    /// Returns only 1 partition if cannot be split further.
822    fn split(self) -> Vec<Self> {
823        if self.batches.len() == 1 {
824            return vec![self];
825        }
826
827        let new_0 = RePartition {
828            idx: self.idx, // output ordering
829            row_count: 0,
830            batches: vec![],
831        };
832        let new_1 = RePartition {
833            idx: self.idx + 1, // output ordering +1
834            row_count: 0,
835            batches: vec![],
836        };
837        let split_pt = self.row_count / 2;
838
839        let [new_0, new_1] = self.batches.into_iter().fold(
840            [new_0, new_1],
841            |[mut new0, mut new1], batch| {
842                if new0.row_count < split_pt {
843                    new0.add_batch(batch);
844                } else {
845                    new1.add_batch(batch);
846                }
847                [new0, new1]
848            },
849        );
850        vec![new_0, new_1]
851    }
852
853    fn add_batch(&mut self, batch: RecordBatch) {
854        self.row_count += batch.num_rows();
855        self.batches.push(batch);
856    }
857}
858
859impl fmt::Display for RePartition {
860    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
861        write!(
862            f,
863            "{}rows-in-{}batches@{}",
864            self.row_count,
865            self.batches.len(),
866            self.idx
867        )
868    }
869}
870
871struct CompareByRowCount(RePartition);
872impl CompareByRowCount {
873    fn into_inner(self) -> RePartition {
874        self.0
875    }
876}
877impl Ord for CompareByRowCount {
878    fn cmp(&self, other: &Self) -> Ordering {
879        self.0.row_count.cmp(&other.0.row_count)
880    }
881}
882impl PartialOrd for CompareByRowCount {
883    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
884        Some(self.cmp(other))
885    }
886}
887impl PartialEq for CompareByRowCount {
888    fn eq(&self, other: &Self) -> bool {
889        // PartialEq must be consistent with PartialOrd
890        self.cmp(other) == Ordering::Equal
891    }
892}
893impl Eq for CompareByRowCount {}
894impl Deref for CompareByRowCount {
895    type Target = RePartition;
896    fn deref(&self) -> &Self::Target {
897        &self.0
898    }
899}
900
901/// Type alias for partition data
902pub type PartitionData = Arc<RwLock<Vec<RecordBatch>>>;
903
904/// Implements for writing to a [`MemTable`]
905///
906/// [`MemTable`]: <https://docs.rs/datafusion/latest/datafusion/datasource/memory/struct.MemTable.html>
907pub struct MemSink {
908    /// Target locations for writing data
909    batches: Vec<PartitionData>,
910    schema: SchemaRef,
911    overwrite: bool,
912}
913
914impl Debug for MemSink {
915    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
916        f.debug_struct("MemSink")
917            .field("num_partitions", &self.batches.len())
918            .finish()
919    }
920}
921
922impl DisplayAs for MemSink {
923    fn fmt_as(&self, t: DisplayFormatType, f: &mut fmt::Formatter<'_>) -> fmt::Result {
924        match t {
925            DisplayFormatType::Default | DisplayFormatType::Verbose => {
926                let partition_count = self.batches.len();
927                write!(f, "MemoryTable (partitions={partition_count})")
928            }
929            DisplayFormatType::TreeRender => {
930                // TODO: collect info
931                write!(f, "")
932            }
933        }
934    }
935}
936
937impl MemSink {
938    /// Creates a new [`MemSink`].
939    ///
940    /// The caller is responsible for ensuring that there is at least one partition to insert into.
941    pub fn try_new(batches: Vec<PartitionData>, schema: SchemaRef) -> Result<Self> {
942        if batches.is_empty() {
943            return plan_err!("Cannot insert into MemTable with zero partitions");
944        }
945        Ok(Self {
946            batches,
947            schema,
948            overwrite: false,
949        })
950    }
951
952    /// Configures whether writes replace the existing data instead of appending to it.
953    pub fn with_overwrite(mut self, overwrite: bool) -> Self {
954        self.overwrite = overwrite;
955        self
956    }
957}
958
959#[async_trait]
960impl DataSink for MemSink {
961    fn schema(&self) -> &SchemaRef {
962        &self.schema
963    }
964
965    async fn write_all(
966        &self,
967        mut data: SendableRecordBatchStream,
968        _context: &Arc<TaskContext>,
969    ) -> Result<u64> {
970        let num_partitions = self.batches.len();
971
972        // buffer up the data round robin style into num_partitions
973
974        let mut new_batches = vec![vec![]; num_partitions];
975        let mut i = 0;
976        let mut row_count = 0;
977        while let Some(batch) = data.next().await.transpose()? {
978            row_count += batch.num_rows();
979            new_batches[i].push(batch);
980            i = (i + 1) % num_partitions;
981        }
982
983        // Modify the table only after the input stream has completed successfully.
984        for (target, mut batches) in self.batches.iter().zip(new_batches) {
985            let mut target = target.write().await;
986            if self.overwrite {
987                *target = batches;
988            } else {
989                // Append all the new batches in one go to minimize locking overhead
990                target.append(&mut batches);
991            }
992        }
993
994        Ok(row_count as u64)
995    }
996}
997
998#[cfg(test)]
999mod memory_source_tests {
1000    use std::sync::Arc;
1001
1002    use crate::memory::MemorySourceConfig;
1003    use crate::source::DataSourceExec;
1004
1005    use arrow::compute::SortOptions;
1006    use arrow::datatypes::{DataType, Field, Schema};
1007    use datafusion_common::Result;
1008    use datafusion_physical_expr::expressions::col;
1009    use datafusion_physical_expr_common::sort_expr::{LexOrdering, PhysicalSortExpr};
1010    use datafusion_physical_plan::ExecutionPlan;
1011
1012    #[test]
1013    fn test_memory_order_eq() -> Result<()> {
1014        let schema = Arc::new(Schema::new(vec![
1015            Field::new("a", DataType::Int64, false),
1016            Field::new("b", DataType::Int64, false),
1017            Field::new("c", DataType::Int64, false),
1018        ]));
1019        let sort1: LexOrdering = [
1020            PhysicalSortExpr {
1021                expr: col("a", &schema)?,
1022                options: SortOptions::default(),
1023            },
1024            PhysicalSortExpr {
1025                expr: col("b", &schema)?,
1026                options: SortOptions::default(),
1027            },
1028        ]
1029        .into();
1030        let sort2: LexOrdering = [PhysicalSortExpr {
1031            expr: col("c", &schema)?,
1032            options: SortOptions::default(),
1033        }]
1034        .into();
1035        let mut expected_output_order = sort1.clone();
1036        expected_output_order.extend(sort2.clone());
1037
1038        let sort_information = vec![sort1.clone(), sort2.clone()];
1039        let mem_exec = DataSourceExec::from_data_source(
1040            MemorySourceConfig::try_new(&[vec![]], schema, None)?
1041                .try_with_sort_information(sort_information)?,
1042        );
1043
1044        assert_eq!(
1045            mem_exec.properties().output_ordering().unwrap(),
1046            &expected_output_order
1047        );
1048        let eq_properties = mem_exec.properties().equivalence_properties();
1049        assert!(eq_properties.oeq_class().contains(&sort1));
1050        assert!(eq_properties.oeq_class().contains(&sort2));
1051        Ok(())
1052    }
1053}
1054
1055#[cfg(test)]
1056mod tests {
1057    use super::*;
1058    use crate::test_util::col;
1059    use crate::tests::{aggr_test_schema, make_partition};
1060
1061    use arrow::array::{ArrayRef, Int32Array, Int64Array, StringArray};
1062    use arrow::datatypes::{DataType, Field};
1063    use datafusion_common::assert_batches_eq;
1064    use datafusion_common::stats::{ColumnStatistics, Precision};
1065    use datafusion_physical_expr::PhysicalSortExpr;
1066    use datafusion_physical_plan::expressions::lit;
1067    use datafusion_physical_plan::statistics::{StatisticsArgs, StatisticsContext};
1068
1069    use datafusion_physical_plan::ExecutionPlan;
1070
1071    #[tokio::test]
1072    async fn exec_with_limit() -> Result<()> {
1073        let task_ctx = Arc::new(TaskContext::default());
1074        let batch = make_partition(7);
1075        let schema = batch.schema();
1076        let batches = vec![batch.clone(), batch];
1077
1078        let exec = MemorySourceConfig::try_new_from_batches(schema, batches).unwrap();
1079        assert_eq!(exec.fetch(), None);
1080
1081        let exec = exec.with_fetch(Some(4)).unwrap();
1082        assert_eq!(exec.fetch(), Some(4));
1083
1084        let mut it = exec.execute(0, task_ctx)?;
1085        let mut results = vec![];
1086        while let Some(batch) = it.next().await {
1087            results.push(batch?);
1088        }
1089
1090        let expected = [
1091            "+---+", "| i |", "+---+", "| 0 |", "| 1 |", "| 2 |", "| 3 |", "+---+",
1092        ];
1093        assert_batches_eq!(expected, &results);
1094        Ok(())
1095    }
1096
1097    /// Test that `try_swapping_with_projection` preserves the `fetch` limit.
1098    /// Regression test for <https://github.com/apache/datafusion/issues/21176>
1099    #[test]
1100    fn try_swapping_with_projection_preserves_fetch() {
1101        use datafusion_physical_expr::projection::ProjectionExprs;
1102
1103        let schema = Arc::new(Schema::new(vec![
1104            Field::new("a", DataType::Int32, false),
1105            Field::new("b", DataType::Utf8, false),
1106            Field::new("c", DataType::Int64, false),
1107        ]));
1108        let partitions: Vec<Vec<RecordBatch>> = vec![vec![batch(10)]];
1109        let source = MemorySourceConfig::try_new(&partitions, schema.clone(), None)
1110            .unwrap()
1111            .with_limit(Some(5));
1112
1113        assert_eq!(source.fetch, Some(5));
1114
1115        // Create a projection that reorders columns: [c, a] (indices 2, 0)
1116        let projection = ProjectionExprs::from_indices(&[2, 0], &schema);
1117        let swapped = source
1118            .try_swapping_with_projection(&projection)
1119            .unwrap()
1120            .unwrap();
1121        let new_source = swapped.downcast_ref::<MemorySourceConfig>().unwrap();
1122
1123        assert_eq!(
1124            new_source.fetch,
1125            Some(5),
1126            "fetch limit must be preserved after projection pushdown"
1127        );
1128    }
1129
1130    #[tokio::test]
1131    async fn values_empty_case() -> Result<()> {
1132        let schema = aggr_test_schema();
1133        let empty = MemorySourceConfig::try_new_as_values(schema, vec![]);
1134        assert!(empty.is_err());
1135        Ok(())
1136    }
1137
1138    #[test]
1139    fn new_exec_with_batches() {
1140        let batch = make_partition(7);
1141        let schema = batch.schema();
1142        let batches = vec![batch.clone(), batch];
1143        let _exec = MemorySourceConfig::try_new_from_batches(schema, batches).unwrap();
1144    }
1145
1146    #[test]
1147    fn new_exec_with_batches_empty() {
1148        let batch = make_partition(7);
1149        let schema = batch.schema();
1150        let _ = MemorySourceConfig::try_new_from_batches(schema, Vec::new()).unwrap_err();
1151    }
1152
1153    #[test]
1154    fn new_exec_with_batches_invalid_schema() {
1155        let batch = make_partition(7);
1156        let batches = vec![batch.clone(), batch];
1157
1158        let invalid_schema = Arc::new(Schema::new(vec![
1159            Field::new("col0", DataType::UInt32, false),
1160            Field::new("col1", DataType::Utf8, false),
1161        ]));
1162        let _ = MemorySourceConfig::try_new_from_batches(invalid_schema, batches)
1163            .unwrap_err();
1164    }
1165
1166    // Test issue: https://github.com/apache/datafusion/issues/8763
1167    #[test]
1168    fn new_exec_with_non_nullable_schema() {
1169        let schema = Arc::new(Schema::new(vec![Field::new(
1170            "col0",
1171            DataType::UInt32,
1172            false,
1173        )]));
1174        let _ = MemorySourceConfig::try_new_as_values(
1175            Arc::clone(&schema),
1176            vec![vec![lit(1u32)]],
1177        )
1178        .unwrap();
1179        // Test that a null value is rejected
1180        let _ = MemorySourceConfig::try_new_as_values(
1181            schema,
1182            vec![vec![lit(ScalarValue::UInt32(None))]],
1183        )
1184        .unwrap_err();
1185    }
1186
1187    #[test]
1188    fn values_stats_with_nulls_only() -> Result<()> {
1189        let data = vec![
1190            vec![lit(ScalarValue::Null)],
1191            vec![lit(ScalarValue::Null)],
1192            vec![lit(ScalarValue::Null)],
1193        ];
1194        let rows = data.len();
1195        let schema =
1196            Arc::new(Schema::new(vec![Field::new("col0", DataType::Null, true)]));
1197        let values = MemorySourceConfig::try_new_as_values(schema, data)?;
1198
1199        assert_eq!(
1200            *StatisticsContext::new().compute(values.as_ref(), &StatisticsArgs::new())?,
1201            Statistics {
1202                num_rows: Precision::Exact(rows),
1203                total_byte_size: Precision::Exact(8), // not important
1204                column_statistics: vec![ColumnStatistics {
1205                    null_count: Precision::Exact(rows), // there are only nulls
1206                    distinct_count: Precision::Absent,
1207                    max_value: Precision::Absent,
1208                    min_value: Precision::Absent,
1209                    sum_value: Precision::Absent,
1210                    byte_size: Precision::Absent,
1211                },],
1212            }
1213        );
1214
1215        Ok(())
1216    }
1217
1218    fn batch(row_size: usize) -> RecordBatch {
1219        let a: ArrayRef = Arc::new(Int32Array::from(vec![1; row_size]));
1220        let b: ArrayRef = Arc::new(StringArray::from_iter(vec![Some("foo"); row_size]));
1221        let c: ArrayRef = Arc::new(Int64Array::from_iter(vec![1; row_size]));
1222        RecordBatch::try_from_iter(vec![("a", a), ("b", b), ("c", c)]).unwrap()
1223    }
1224
1225    fn schema() -> SchemaRef {
1226        batch(1).schema()
1227    }
1228
1229    fn memorysrcconfig_no_partitions(
1230        sort_information: Vec<LexOrdering>,
1231    ) -> Result<MemorySourceConfig> {
1232        let partitions = vec![];
1233        MemorySourceConfig::try_new(&partitions, schema(), None)?
1234            .try_with_sort_information(sort_information)
1235    }
1236
1237    fn memorysrcconfig_1_partition_1_batch(
1238        sort_information: Vec<LexOrdering>,
1239    ) -> Result<MemorySourceConfig> {
1240        let partitions = vec![vec![batch(100)]];
1241        MemorySourceConfig::try_new(&partitions, schema(), None)?
1242            .try_with_sort_information(sort_information)
1243    }
1244
1245    fn memorysrcconfig_3_partitions_1_batch_each(
1246        sort_information: Vec<LexOrdering>,
1247    ) -> Result<MemorySourceConfig> {
1248        let partitions = vec![vec![batch(100)], vec![batch(100)], vec![batch(100)]];
1249        MemorySourceConfig::try_new(&partitions, schema(), None)?
1250            .try_with_sort_information(sort_information)
1251    }
1252
1253    fn memorysrcconfig_3_partitions_with_2_batches_each(
1254        sort_information: Vec<LexOrdering>,
1255    ) -> Result<MemorySourceConfig> {
1256        let partitions = vec![
1257            vec![batch(100), batch(100)],
1258            vec![batch(100), batch(100)],
1259            vec![batch(100), batch(100)],
1260        ];
1261        MemorySourceConfig::try_new(&partitions, schema(), None)?
1262            .try_with_sort_information(sort_information)
1263    }
1264
1265    /// Batches of different sizes, with batches ordered by size (100_000, 10_000, 100, 1)
1266    /// in the Memtable partition (a.k.a. vector of batches).
1267    fn memorysrcconfig_1_partition_with_different_sized_batches(
1268        sort_information: Vec<LexOrdering>,
1269    ) -> Result<MemorySourceConfig> {
1270        let partitions = vec![vec![batch(100_000), batch(10_000), batch(100), batch(1)]];
1271        MemorySourceConfig::try_new(&partitions, schema(), None)?
1272            .try_with_sort_information(sort_information)
1273    }
1274
1275    /// Same as [`memorysrcconfig_1_partition_with_different_sized_batches`],
1276    /// but the batches are ordered differently (not by size)
1277    /// in the Memtable partition (a.k.a. vector of batches).
1278    fn memorysrcconfig_1_partition_with_ordering_not_matching_size(
1279        sort_information: Vec<LexOrdering>,
1280    ) -> Result<MemorySourceConfig> {
1281        let partitions = vec![vec![batch(100_000), batch(1), batch(100), batch(10_000)]];
1282        MemorySourceConfig::try_new(&partitions, schema(), None)?
1283            .try_with_sort_information(sort_information)
1284    }
1285
1286    fn memorysrcconfig_2_partition_with_different_sized_batches(
1287        sort_information: Vec<LexOrdering>,
1288    ) -> Result<MemorySourceConfig> {
1289        let partitions = vec![
1290            vec![batch(100_000), batch(10_000), batch(1_000)],
1291            vec![batch(2_000), batch(20)],
1292        ];
1293        MemorySourceConfig::try_new(&partitions, schema(), None)?
1294            .try_with_sort_information(sort_information)
1295    }
1296
1297    fn memorysrcconfig_2_partition_with_extreme_sized_batches(
1298        sort_information: Vec<LexOrdering>,
1299    ) -> Result<MemorySourceConfig> {
1300        let partitions = vec![
1301            vec![
1302                batch(100_000),
1303                batch(1),
1304                batch(1),
1305                batch(1),
1306                batch(1),
1307                batch(0),
1308            ],
1309            vec![batch(1), batch(1), batch(1), batch(1), batch(0), batch(100)],
1310        ];
1311        MemorySourceConfig::try_new(&partitions, schema(), None)?
1312            .try_with_sort_information(sort_information)
1313    }
1314
1315    /// Assert that we get the expected count of partitions after repartitioning.
1316    ///
1317    /// If None, then we expected the [`DataSource::repartitioned`] to return None.
1318    fn assert_partitioning(
1319        partitioned_datasrc: Option<Arc<dyn DataSource>>,
1320        partition_cnt: Option<usize>,
1321    ) {
1322        let should_exist = if let Some(partition_cnt) = partition_cnt {
1323            format!("new datasource should exist and have {partition_cnt:?} partitions")
1324        } else {
1325            "new datasource should not exist".into()
1326        };
1327
1328        let actual = partitioned_datasrc
1329            .map(|datasrc| datasrc.output_partitioning().partition_count());
1330        assert_eq!(
1331            actual, partition_cnt,
1332            "partitioned datasrc does not match expected, we expected {should_exist}, instead found {actual:?}"
1333        );
1334    }
1335
1336    fn run_all_test_scenarios(
1337        output_ordering: Option<LexOrdering>,
1338        sort_information_on_config: Vec<LexOrdering>,
1339    ) -> Result<()> {
1340        let not_used = usize::MAX;
1341
1342        // src has no partitions
1343        let mem_src_config =
1344            memorysrcconfig_no_partitions(sort_information_on_config.clone())?;
1345        let partitioned_datasrc =
1346            mem_src_config.repartitioned(1, not_used, output_ordering.clone())?;
1347        assert_partitioning(partitioned_datasrc, None);
1348
1349        // src has partitions == target partitions (=1)
1350        let target_partitions = 1;
1351        let mem_src_config =
1352            memorysrcconfig_1_partition_1_batch(sort_information_on_config.clone())?;
1353        let partitioned_datasrc = mem_src_config.repartitioned(
1354            target_partitions,
1355            not_used,
1356            output_ordering.clone(),
1357        )?;
1358        assert_partitioning(partitioned_datasrc, None);
1359
1360        // src has partitions == target partitions (=3)
1361        let target_partitions = 3;
1362        let mem_src_config = memorysrcconfig_3_partitions_1_batch_each(
1363            sort_information_on_config.clone(),
1364        )?;
1365        let partitioned_datasrc = mem_src_config.repartitioned(
1366            target_partitions,
1367            not_used,
1368            output_ordering.clone(),
1369        )?;
1370        assert_partitioning(partitioned_datasrc, None);
1371
1372        // src has partitions > target partitions, but we don't merge them
1373        let target_partitions = 2;
1374        let mem_src_config = memorysrcconfig_3_partitions_1_batch_each(
1375            sort_information_on_config.clone(),
1376        )?;
1377        let partitioned_datasrc = mem_src_config.repartitioned(
1378            target_partitions,
1379            not_used,
1380            output_ordering.clone(),
1381        )?;
1382        assert_partitioning(partitioned_datasrc, None);
1383
1384        // src has partitions < target partitions, but not enough batches (per partition) to split into more partitions
1385        let target_partitions = 4;
1386        let mem_src_config = memorysrcconfig_3_partitions_1_batch_each(
1387            sort_information_on_config.clone(),
1388        )?;
1389        let partitioned_datasrc = mem_src_config.repartitioned(
1390            target_partitions,
1391            not_used,
1392            output_ordering.clone(),
1393        )?;
1394        assert_partitioning(partitioned_datasrc, None);
1395
1396        // src has partitions < target partitions, and can split to sufficient amount
1397        // has 6 batches across 3 partitions. Will need to split 2 of it's partitions.
1398        let target_partitions = 5;
1399        let mem_src_config = memorysrcconfig_3_partitions_with_2_batches_each(
1400            sort_information_on_config.clone(),
1401        )?;
1402        let partitioned_datasrc = mem_src_config.repartitioned(
1403            target_partitions,
1404            not_used,
1405            output_ordering.clone(),
1406        )?;
1407        assert_partitioning(partitioned_datasrc, Some(5));
1408
1409        // src has partitions < target partitions, and can split to sufficient amount
1410        // has 6 batches across 3 partitions. Will need to split all of it's partitions.
1411        let target_partitions = 6;
1412        let mem_src_config = memorysrcconfig_3_partitions_with_2_batches_each(
1413            sort_information_on_config.clone(),
1414        )?;
1415        let partitioned_datasrc = mem_src_config.repartitioned(
1416            target_partitions,
1417            not_used,
1418            output_ordering.clone(),
1419        )?;
1420        assert_partitioning(partitioned_datasrc, Some(6));
1421
1422        // src has partitions < target partitions, but not enough total batches to fulfill the split (desired target_partitions)
1423        let target_partitions = 3 * 2 + 1;
1424        let mem_src_config = memorysrcconfig_3_partitions_with_2_batches_each(
1425            sort_information_on_config.clone(),
1426        )?;
1427        let partitioned_datasrc = mem_src_config.repartitioned(
1428            target_partitions,
1429            not_used,
1430            output_ordering.clone(),
1431        )?;
1432        assert_partitioning(partitioned_datasrc, None);
1433
1434        // src has 1 partition with many batches of lopsided sizes
1435        // make sure it handles the split properly
1436        let target_partitions = 2;
1437        let mem_src_config = memorysrcconfig_1_partition_with_different_sized_batches(
1438            sort_information_on_config,
1439        )?;
1440        let partitioned_datasrc = mem_src_config.clone().repartitioned(
1441            target_partitions,
1442            not_used,
1443            output_ordering,
1444        )?;
1445        assert_partitioning(partitioned_datasrc.clone(), Some(2));
1446        // Starting = batch(100_000), batch(10_000), batch(100), batch(1).
1447        // It should have split as p1=batch(100_000), p2=[batch(10_000), batch(100), batch(1)]
1448        let partitioned_datasrc = partitioned_datasrc.unwrap();
1449        let Some(mem_src_config) =
1450            partitioned_datasrc.downcast_ref::<MemorySourceConfig>()
1451        else {
1452            unreachable!()
1453        };
1454        let repartitioned_raw_batches = mem_src_config.partitions.clone();
1455        assert_eq!(repartitioned_raw_batches.len(), 2);
1456        let [ref p1, ref p2] = repartitioned_raw_batches[..] else {
1457            unreachable!()
1458        };
1459        // p1=batch(100_000)
1460        assert_eq!(p1.len(), 1);
1461        assert_eq!(p1[0].num_rows(), 100_000);
1462        // p2=[batch(10_000), batch(100), batch(1)]
1463        assert_eq!(p2.len(), 3);
1464        assert_eq!(p2[0].num_rows(), 10_000);
1465        assert_eq!(p2[1].num_rows(), 100);
1466        assert_eq!(p2[2].num_rows(), 1);
1467
1468        Ok(())
1469    }
1470
1471    #[test]
1472    fn test_repartition_no_sort_information_no_output_ordering() -> Result<()> {
1473        let no_sort = vec![];
1474        let no_output_ordering = None;
1475
1476        // Test: common set of functionality
1477        run_all_test_scenarios(no_output_ordering.clone(), no_sort.clone())?;
1478
1479        // Test: how no-sort-order divides differently.
1480        //    * does not preserve separate partitions (with own internal ordering) on even split,
1481        //    * nor does it preserve ordering (re-orders batch(2_000) vs batch(1_000)).
1482        let target_partitions = 3;
1483        let mem_src_config =
1484            memorysrcconfig_2_partition_with_different_sized_batches(no_sort)?;
1485        let partitioned_datasrc = mem_src_config.clone().repartitioned(
1486            target_partitions,
1487            usize::MAX,
1488            no_output_ordering,
1489        )?;
1490        assert_partitioning(partitioned_datasrc.clone(), Some(3));
1491        // Starting = batch(100_000), batch(10_000), batch(1_000), batch(2_000), batch(20)
1492        // It should have split as p1=batch(100_000), p2=batch(10_000),  p3=rest(mixed across original partitions)
1493        let repartitioned_raw_batches = mem_src_config
1494            .repartition_evenly_by_size(target_partitions)?
1495            .unwrap();
1496        assert_eq!(repartitioned_raw_batches.len(), 3);
1497        let [ref p1, ref p2, ref p3] = repartitioned_raw_batches[..] else {
1498            unreachable!()
1499        };
1500        // p1=batch(100_000)
1501        assert_eq!(p1.len(), 1);
1502        assert_eq!(p1[0].num_rows(), 100_000);
1503        // p2=batch(10_000)
1504        assert_eq!(p2.len(), 1);
1505        assert_eq!(p2[0].num_rows(), 10_000);
1506        // p3= batch(2_000), batch(1_000), batch(20)
1507        assert_eq!(p3.len(), 3);
1508        assert_eq!(p3[0].num_rows(), 2_000);
1509        assert_eq!(p3[1].num_rows(), 1_000);
1510        assert_eq!(p3[2].num_rows(), 20);
1511
1512        Ok(())
1513    }
1514
1515    #[test]
1516    fn test_repartition_no_sort_information_no_output_ordering_lopsized_batches()
1517    -> Result<()> {
1518        let no_sort = vec![];
1519        let no_output_ordering = None;
1520
1521        // Test: case has two input partitions:
1522        //     b(100_000), b(1), b(1), b(1), b(1), b(0)
1523        //     b(1), b(1), b(1), b(1), b(0), b(100)
1524        //
1525        // We want an output with target_partitions=5, which means the ideal division is:
1526        //     b(100_000)
1527        //     b(100)
1528        //     b(1), b(1), b(1)
1529        //     b(1), b(1), b(1)
1530        //     b(1), b(1), b(0)
1531        let target_partitions = 5;
1532        let mem_src_config =
1533            memorysrcconfig_2_partition_with_extreme_sized_batches(no_sort)?;
1534        let partitioned_datasrc = mem_src_config.clone().repartitioned(
1535            target_partitions,
1536            usize::MAX,
1537            no_output_ordering,
1538        )?;
1539        assert_partitioning(partitioned_datasrc.clone(), Some(5));
1540        // Starting partition 1 = batch(100_000), batch(1), batch(1), batch(1), batch(1), batch(0)
1541        // Starting partition 1 = batch(1), batch(1), batch(1), batch(1), batch(0), batch(100)
1542        // It should have split as p1=batch(100_000), p2=batch(100), p3=[batch(1),batch(1)], p4=[batch(1),batch(1)], p5=[batch(1),batch(1),batch(0),batch(0)]
1543        let repartitioned_raw_batches = mem_src_config
1544            .repartition_evenly_by_size(target_partitions)?
1545            .unwrap();
1546        assert_eq!(repartitioned_raw_batches.len(), 5);
1547        let [ref p1, ref p2, ref p3, ref p4, ref p5] = repartitioned_raw_batches[..]
1548        else {
1549            unreachable!()
1550        };
1551        // p1=batch(100_000)
1552        assert_eq!(p1.len(), 1);
1553        assert_eq!(p1[0].num_rows(), 100_000);
1554        // p2=batch(100)
1555        assert_eq!(p2.len(), 1);
1556        assert_eq!(p2[0].num_rows(), 100);
1557        // p3=[batch(1),batch(1),batch(1)]
1558        assert_eq!(p3.len(), 3);
1559        assert_eq!(p3[0].num_rows(), 1);
1560        assert_eq!(p3[1].num_rows(), 1);
1561        assert_eq!(p3[2].num_rows(), 1);
1562        // p4=[batch(1),batch(1),batch(1)]
1563        assert_eq!(p4.len(), 3);
1564        assert_eq!(p4[0].num_rows(), 1);
1565        assert_eq!(p4[1].num_rows(), 1);
1566        assert_eq!(p4[2].num_rows(), 1);
1567        // p5=[batch(1),batch(1),batch(0),batch(0)]
1568        assert_eq!(p5.len(), 4);
1569        assert_eq!(p5[0].num_rows(), 1);
1570        assert_eq!(p5[1].num_rows(), 1);
1571        assert_eq!(p5[2].num_rows(), 0);
1572        assert_eq!(p5[3].num_rows(), 0);
1573
1574        Ok(())
1575    }
1576
1577    #[test]
1578    fn test_repartition_with_sort_information() -> Result<()> {
1579        let schema = schema();
1580        let sort_key: LexOrdering =
1581            [PhysicalSortExpr::new_default(col("c", &schema)?)].into();
1582        let has_sort = vec![sort_key.clone()];
1583        let output_ordering = Some(sort_key);
1584
1585        // Test: common set of functionality
1586        run_all_test_scenarios(output_ordering.clone(), has_sort.clone())?;
1587
1588        // Test: DOES preserve separate partitions (with own internal ordering)
1589        let target_partitions = 3;
1590        let mem_src_config =
1591            memorysrcconfig_2_partition_with_different_sized_batches(has_sort)?;
1592        let partitioned_datasrc = mem_src_config.clone().repartitioned(
1593            target_partitions,
1594            usize::MAX,
1595            output_ordering.clone(),
1596        )?;
1597        assert_partitioning(partitioned_datasrc.clone(), Some(3));
1598        // Starting = batch(100_000), batch(10_000), batch(1_000), batch(2_000), batch(20)
1599        // It should have split as p1=batch(100_000), p2=[batch(10_000),batch(1_000)],  p3=<other_partition>
1600        let Some(output_ord) = output_ordering else {
1601            unreachable!()
1602        };
1603        let repartitioned_raw_batches = mem_src_config
1604            .repartition_preserving_order(target_partitions, output_ord)?
1605            .unwrap();
1606        assert_eq!(repartitioned_raw_batches.len(), 3);
1607        let [ref p1, ref p2, ref p3] = repartitioned_raw_batches[..] else {
1608            unreachable!()
1609        };
1610        // p1=batch(100_000)
1611        assert_eq!(p1.len(), 1);
1612        assert_eq!(p1[0].num_rows(), 100_000);
1613        // p2=[batch(10_000),batch(1_000)]
1614        assert_eq!(p2.len(), 2);
1615        assert_eq!(p2[0].num_rows(), 10_000);
1616        assert_eq!(p2[1].num_rows(), 1_000);
1617        // p3=batch(2_000), batch(20)
1618        assert_eq!(p3.len(), 2);
1619        assert_eq!(p3[0].num_rows(), 2_000);
1620        assert_eq!(p3[1].num_rows(), 20);
1621
1622        Ok(())
1623    }
1624
1625    #[test]
1626    fn test_repartition_with_batch_ordering_not_matching_sizing() -> Result<()> {
1627        let schema = schema();
1628        let sort_key: LexOrdering =
1629            [PhysicalSortExpr::new_default(col("c", &schema)?)].into();
1630        let has_sort = vec![sort_key.clone()];
1631        let output_ordering = Some(sort_key);
1632
1633        // src has 1 partition with many batches of lopsided sizes
1634        // note that the input vector of batches are not ordered by decreasing size
1635        let target_partitions = 2;
1636        let mem_src_config =
1637            memorysrcconfig_1_partition_with_ordering_not_matching_size(has_sort)?;
1638        let partitioned_datasrc = mem_src_config.clone().repartitioned(
1639            target_partitions,
1640            usize::MAX,
1641            output_ordering,
1642        )?;
1643        assert_partitioning(partitioned_datasrc.clone(), Some(2));
1644        // Starting = batch(100_000), batch(1), batch(100), batch(10_000).
1645        // It should have split as p1=batch(100_000), p2=[batch(1), batch(100), batch(10_000)]
1646        let partitioned_datasrc = partitioned_datasrc.unwrap();
1647        let Some(mem_src_config) =
1648            partitioned_datasrc.downcast_ref::<MemorySourceConfig>()
1649        else {
1650            unreachable!()
1651        };
1652        let repartitioned_raw_batches = mem_src_config.partitions.clone();
1653        assert_eq!(repartitioned_raw_batches.len(), 2);
1654        let [ref p1, ref p2] = repartitioned_raw_batches[..] else {
1655            unreachable!()
1656        };
1657        // p1=batch(100_000)
1658        assert_eq!(p1.len(), 1);
1659        assert_eq!(p1[0].num_rows(), 100_000);
1660        // p2=[batch(1), batch(100), batch(10_000)] -- **this is preserving the partition order**
1661        assert_eq!(p2.len(), 3);
1662        assert_eq!(p2[0].num_rows(), 1);
1663        assert_eq!(p2[1].num_rows(), 100);
1664        assert_eq!(p2[2].num_rows(), 10_000);
1665
1666        Ok(())
1667    }
1668}