datafusion-physical-plan 56.0.0

Physical (ExecutionPlan) implementations for DataFusion query engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements

//! Defines the Sort-Merge join execution plan.
//! A Sort-Merge join plan consumes two sorted children plans and produces
//! joined output by given join type and other options.

use std::fmt::Formatter;
use std::sync::Arc;

use super::bitwise_stream::BitwiseSortMergeJoinStream;
use super::materializing_stream::MaterializingSortMergeJoinStream;
use super::metrics::SortMergeJoinMetrics;
use crate::execution_plan::{EmissionType, boundedness_from_children};
use crate::expressions::PhysicalSortExpr;
use crate::joins::utils::{
    JoinFilter, JoinOn, JoinOnRef, build_join_schema, check_join_is_valid,
    estimate_join_statistics, reorder_output_after_swap, swap_join_projection,
    symmetric_join_output_partitioning,
};
use crate::metrics::{ExecutionPlanMetricsSet, MetricsSet, SpillMetrics};
use crate::projection::{
    EmbeddedProjection, JoinData, ProjectionExec, try_embed_projection,
    try_pushdown_through_join_with_column_indices,
};
use crate::spill::spill_manager::SpillManager;
use crate::statistics::{ChildStats, StatisticsArgs};
use crate::stream::RecordBatchStreamAdapter;
use crate::{
    ChildrenPropertiesMode, DisplayAs, DisplayFormatType, Distribution, ExecutionPlan,
    ExecutionPlanProperties, InputDistributionRequirements, PlanProperties,
    ReplaceChildrenOptions, SendableRecordBatchStream, Statistics, common::can_project,
    validate_child_count,
};

use arrow::compute::SortOptions;
use arrow::datatypes::SchemaRef;
use datafusion_common::project_schema;
use datafusion_common::tree_node::TreeNodeRecursion;
use datafusion_common::{
    JoinSide, JoinType, NullEquality, Result, assert_eq_or_internal_err, internal_err,
    plan_err,
};
use datafusion_execution::TaskContext;
use datafusion_execution::memory_pool::MemoryConsumer;
use datafusion_physical_expr::equivalence::{
    ProjectionMapping, join_equivalence_properties,
};
use datafusion_physical_expr_common::physical_expr::{PhysicalExprRef, fmt_sql};
use datafusion_physical_expr_common::sort_expr::{LexOrdering, OrderingRequirements};
use futures::StreamExt;

/// Join execution plan that executes equi-join predicates on multiple partitions using Sort-Merge
/// join algorithm and applies an optional filter post join. Can be used to join arbitrarily large
/// inputs where one or both of the inputs don't fit in the available memory.
///
/// # Join Expressions
///
/// Equi-join predicate (e.g. `<col1> = <col2>`) expressions are represented by [`Self::on`].
///
/// Non-equality predicates, which can not be pushed down to join inputs (e.g.
/// `<col1> != <col2>`) are known as "filter expressions" and are evaluated
/// after the equijoin predicates. They are represented by [`Self::filter`]. These are optional
/// expressions.
///
/// # Sorting
///
/// Assumes that both the left and right input to the join are pre-sorted. It is not the
/// responsibility of this execution plan to sort the inputs.
///
/// # "Streamed" vs "Buffered"
///
/// The number of record batches of streamed input currently present in the memory will depend
/// on the output batch size of the execution plan. There is no spilling support for streamed input.
/// The comparisons are performed from values of join keys in streamed input with the values of
/// join keys in buffered input. One row in streamed record batch could be matched with multiple rows in
/// buffered input batches. Streamed input batches are represented by `StreamedBatch`.
///
/// Buffered input is buffered for all record batches having the same value of join key.
/// If the memory limit increases beyond the specified value and spilling is enabled,
/// buffered batches could be spilled to disk. If spilling is disabled, the execution
/// will fail under the same conditions. Multiple record batches of buffered could currently reside
/// in memory/disk during the execution. The number of buffered batches residing in
/// memory/disk depends on the number of rows of buffered input having the same value
/// of join key as that of streamed input rows currently present in memory. Due to pre-sorted inputs,
/// the algorithm understands when it is not needed anymore, and releases the buffered batches
/// from memory/disk. Buffered input batches are represented by `BufferedBatch`.
///
/// Depending on the type of join, left or right input may be selected as streamed or buffered
/// respectively. For example, in a left-outer join, the left execution plan will be selected as
/// streamed input while in a right-outer join, the right execution plan will be selected as the
/// streamed input.
///
/// Reference for the algorithm:
/// <https://en.wikipedia.org/wiki/Sort-merge_join>.
///
/// Helpful short video demonstration:
/// <https://www.youtube.com/watch?v=jiWCPJtDE2c>.
#[derive(Debug, Clone)]
pub struct SortMergeJoinExec {
    /// Left sorted joining execution plan
    pub left: Arc<dyn ExecutionPlan>,
    /// Right sorting joining execution plan
    pub right: Arc<dyn ExecutionPlan>,
    /// Set of common columns used to join on
    pub on: JoinOn,
    /// Filters which are applied while finding matching rows
    pub filter: Option<JoinFilter>,
    /// How the join is performed
    pub join_type: JoinType,
    /// The schema once the join is applied
    schema: SchemaRef,
    /// Execution metrics
    metrics: ExecutionPlanMetricsSet,
    /// The left SortExpr
    left_sort_exprs: LexOrdering,
    /// The right SortExpr
    right_sort_exprs: LexOrdering,
    /// Sort options of join columns used in sorting left and right execution plans
    pub sort_options: Vec<SortOptions>,
    /// Defines the null equality for the join.
    pub null_equality: NullEquality,
    /// The columns of `schema` to emit, in order. `None` emits all of them.
    pub projection: Option<Vec<usize>>,
    /// Cache holding plan properties like equivalences, output partitioning etc.
    cache: Arc<PlanProperties>,
}

impl SortMergeJoinExec {
    /// Tries to create a new [SortMergeJoinExec].
    /// The inputs are sorted using `sort_options` are applied to the columns in the `on`
    /// # Error
    /// This function errors when it is not possible to join the left and right sides on keys `on`.
    pub fn try_new(
        left: Arc<dyn ExecutionPlan>,
        right: Arc<dyn ExecutionPlan>,
        on: JoinOn,
        filter: Option<JoinFilter>,
        join_type: JoinType,
        sort_options: Vec<SortOptions>,
        null_equality: NullEquality,
    ) -> Result<Self> {
        let left_schema = left.schema();
        let right_schema = right.schema();

        check_join_is_valid(&left_schema, &right_schema, &on)?;
        if sort_options.len() != on.len() {
            return plan_err!(
                "Expected number of sort options: {}, actual: {}",
                on.len(),
                sort_options.len()
            );
        }

        let (left_sort_exprs, right_sort_exprs): (Vec<_>, Vec<_>) = on
            .iter()
            .zip(sort_options.iter())
            .map(|((l, r), sort_op)| {
                let left = PhysicalSortExpr {
                    expr: Arc::clone(l),
                    options: *sort_op,
                };
                let right = PhysicalSortExpr {
                    expr: Arc::clone(r),
                    options: *sort_op,
                };
                (left, right)
            })
            .unzip();
        let Some(left_sort_exprs) = LexOrdering::new(left_sort_exprs) else {
            return plan_err!(
                "SortMergeJoinExec requires valid sort expressions for its left side"
            );
        };
        let Some(right_sort_exprs) = LexOrdering::new(right_sort_exprs) else {
            return plan_err!(
                "SortMergeJoinExec requires valid sort expressions for its right side"
            );
        };

        let schema =
            Arc::new(build_join_schema(&left_schema, &right_schema, &join_type).0);
        let cache =
            Self::compute_properties(&left, &right, &schema, join_type, &on, None)?;
        Ok(Self {
            left,
            right,
            on,
            filter,
            join_type,
            schema,
            metrics: ExecutionPlanMetricsSet::new(),
            left_sort_exprs,
            right_sort_exprs,
            sort_options,
            null_equality,
            projection: None,
            cache: Arc::new(cache),
        })
    }

    /// Returns this join emitting only the columns in `projection`, in that order.
    /// The indices address the join's own schema, before any projection.
    pub fn with_projection(&self, projection: Option<Vec<usize>>) -> Result<Self> {
        can_project(&self.schema, projection.as_deref())?;
        let cache = Self::compute_properties(
            &self.left,
            &self.right,
            &self.schema,
            self.join_type,
            &self.on,
            projection.as_deref(),
        )?;
        Ok(Self {
            projection,
            metrics: ExecutionPlanMetricsSet::new(),
            cache: Arc::new(cache),
            ..Self::clone(self)
        })
    }

    /// Get probe side (e.g streaming side) information for this sort merge join.
    /// In current implementation, probe side is determined according to join type.
    pub fn probe_side(join_type: &JoinType) -> JoinSide {
        // When output schema contains only the right side, probe side is right.
        // Otherwise probe side is the left side.
        match join_type {
            // TODO: sort merge support for right mark (tracked here: https://github.com/apache/datafusion/issues/16226)
            JoinType::Right
            | JoinType::RightSemi
            | JoinType::RightAnti
            | JoinType::RightMark => JoinSide::Right,
            JoinType::Inner
            | JoinType::Left
            | JoinType::Full
            | JoinType::LeftAnti
            | JoinType::LeftSemi
            | JoinType::LeftMark => JoinSide::Left,
        }
    }

    /// Calculate order preservation flags for this sort merge join.
    fn maintains_input_order(join_type: JoinType) -> Vec<bool> {
        match join_type {
            JoinType::Inner => vec![true, false],
            JoinType::Left
            | JoinType::LeftSemi
            | JoinType::LeftAnti
            | JoinType::LeftMark => vec![true, false],
            JoinType::Right
            | JoinType::RightSemi
            | JoinType::RightAnti
            | JoinType::RightMark => {
                vec![false, true]
            }
            _ => vec![false, false],
        }
    }

    /// Set of common columns used to join on
    pub fn on(&self) -> &[(PhysicalExprRef, PhysicalExprRef)] {
        &self.on
    }

    /// Ref to right execution plan
    pub fn right(&self) -> &Arc<dyn ExecutionPlan> {
        &self.right
    }

    /// Join type
    pub fn join_type(&self) -> JoinType {
        self.join_type
    }

    /// Ref to left execution plan
    pub fn left(&self) -> &Arc<dyn ExecutionPlan> {
        &self.left
    }

    /// Ref to join filter
    pub fn filter(&self) -> &Option<JoinFilter> {
        &self.filter
    }

    /// Ref to sort options
    pub fn sort_options(&self) -> &[SortOptions] {
        &self.sort_options
    }

    /// Null equality
    pub fn null_equality(&self) -> NullEquality {
        self.null_equality
    }

    /// This function creates the cache object that stores the plan properties such as schema, equivalence properties, ordering, partitioning, etc.
    fn compute_properties(
        left: &Arc<dyn ExecutionPlan>,
        right: &Arc<dyn ExecutionPlan>,
        schema: &SchemaRef,
        join_type: JoinType,
        join_on: JoinOnRef,
        projection: Option<&[usize]>,
    ) -> Result<PlanProperties> {
        // Calculate equivalence properties:
        let mut eq_properties = join_equivalence_properties(
            left.equivalence_properties().clone(),
            right.equivalence_properties().clone(),
            &join_type,
            Arc::clone(schema),
            &Self::maintains_input_order(join_type),
            Some(Self::probe_side(&join_type)),
            join_on,
        )?;

        let mut output_partitioning =
            symmetric_join_output_partitioning(left, right, &join_type)?;

        if let Some(projection) = projection {
            let mapping = ProjectionMapping::from_indices(projection, schema)?;
            let projected = project_schema(schema, Some(projection))?;
            output_partitioning = output_partitioning.project(&mapping, &eq_properties);
            eq_properties = eq_properties.project(&mapping, projected);
        }

        Ok(PlanProperties::new(
            eq_properties,
            output_partitioning,
            EmissionType::Incremental,
            boundedness_from_children([left, right]),
        ))
    }

    /// # Notes:
    ///
    /// This function should be called BEFORE inserting any repartitioning
    /// operators on the join's children. Check [`super::super::HashJoinExec::swap_inputs`]
    /// for more details.
    ///
    /// # Public Only for Internal Use:
    ///
    /// This is not a public API and is for internal use only; see [API policy] for details.
    ///
    /// Direct use of this API in downstream projects is discouraged because
    /// correctness depends on strict preconditions. See the notes above for
    /// correct usage.
    ///
    /// This API may change frequently as internal join optimizations evolve.
    ///
    /// [API policy]: https://datafusion.apache.org/contributor-guide/api-health.html#internal-public-apis
    #[doc(hidden)]
    pub fn swap_inputs(&self) -> Result<Arc<dyn ExecutionPlan>> {
        let left = self.left();
        let right = self.right();
        let new_join = SortMergeJoinExec::try_new(
            Arc::clone(right),
            Arc::clone(left),
            self.on()
                .iter()
                .map(|(l, r)| (Arc::clone(r), Arc::clone(l)))
                .collect::<Vec<_>>(),
            self.filter().as_ref().map(JoinFilter::swap),
            self.join_type().swap(),
            self.sort_options.clone(),
            self.null_equality,
        )?
        .with_projection(swap_join_projection(
            left.schema().fields().len(),
            right.schema().fields().len(),
            self.projection.as_deref(),
            &self.join_type(),
        ))?;

        // A semi, anti or mark join emits one side, and a projection already names the
        // columns to emit, so in both cases swapping leaves the output order alone.
        if matches!(
            self.join_type(),
            JoinType::LeftSemi
                | JoinType::RightSemi
                | JoinType::LeftAnti
                | JoinType::RightAnti
                | JoinType::LeftMark
                | JoinType::RightMark
        ) || self.projection.is_some()
        {
            Ok(Arc::new(new_join))
        } else {
            reorder_output_after_swap(Arc::new(new_join), &left.schema(), &right.schema())
        }
    }
}

impl EmbeddedProjection for SortMergeJoinExec {
    fn with_projection(&self, projection: Option<Vec<usize>>) -> Result<Self> {
        self.with_projection(projection)
    }
}

impl DisplayAs for SortMergeJoinExec {
    fn fmt_as(&self, t: DisplayFormatType, f: &mut Formatter) -> std::fmt::Result {
        match t {
            DisplayFormatType::Default | DisplayFormatType::Verbose => {
                let on = self
                    .on
                    .iter()
                    .map(|(c1, c2)| format!("({c1}, {c2})"))
                    .collect::<Vec<String>>()
                    .join(", ");
                let display_null_equality =
                    if self.null_equality() == NullEquality::NullEqualsNull {
                        ", NullsEqual: true"
                    } else {
                        ""
                    };
                let display_projections = match &self.projection {
                    Some(projection) => format!(
                        ", projection=[{}]",
                        projection
                            .iter()
                            .map(|index| format!(
                                "{}@{}",
                                self.schema.field(*index).name(),
                                index
                            ))
                            .collect::<Vec<_>>()
                            .join(", ")
                    ),
                    None => String::new(),
                };
                write!(
                    f,
                    "{}: join_type={:?}, on=[{}]{}{}{}",
                    Self::static_name(),
                    self.join_type,
                    on,
                    self.filter.as_ref().map_or_else(
                        || "".to_string(),
                        |f| format!(", filter={}", f.expression())
                    ),
                    display_null_equality,
                    display_projections,
                )
            }
            DisplayFormatType::TreeRender => {
                let on = self
                    .on
                    .iter()
                    .map(|(c1, c2)| {
                        format!("({} = {})", fmt_sql(c1.as_ref()), fmt_sql(c2.as_ref()))
                    })
                    .collect::<Vec<String>>()
                    .join(", ");

                if self.join_type() != JoinType::Inner {
                    writeln!(f, "join_type={:?}", self.join_type)?;
                }
                writeln!(f, "on={on}")?;

                if self.null_equality() == NullEquality::NullEqualsNull {
                    writeln!(f, "NullsEqual: true")?;
                }

                Ok(())
            }
        }
    }
}

impl ExecutionPlan for SortMergeJoinExec {
    fn name(&self) -> &'static str {
        "SortMergeJoinExec"
    }

    fn properties(&self) -> &Arc<PlanProperties> {
        &self.cache
    }

    fn required_input_distribution(&self) -> Vec<Distribution> {
        self.input_distribution_requirements().into_per_child()
    }

    fn input_distribution_requirements(&self) -> InputDistributionRequirements {
        let (left_expr, right_expr) = self
            .on
            .iter()
            .map(|(l, r)| (Arc::clone(l), Arc::clone(r)))
            .unzip();
        InputDistributionRequirements::co_partitioned(vec![
            Distribution::KeyPartitioned(left_expr),
            Distribution::KeyPartitioned(right_expr),
        ])
    }

    fn required_input_ordering(&self) -> Vec<Option<OrderingRequirements>> {
        vec![
            Some(OrderingRequirements::from(self.left_sort_exprs.clone())),
            Some(OrderingRequirements::from(self.right_sort_exprs.clone())),
        ]
    }

    fn maintains_input_order(&self) -> Vec<bool> {
        Self::maintains_input_order(self.join_type)
    }

    fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
        vec![&self.left, &self.right]
    }

    fn apply_expressions(
        &self,
        f: &mut dyn FnMut(&Arc<dyn crate::PhysicalExpr>) -> Result<TreeNodeRecursion>,
    ) -> Result<TreeNodeRecursion> {
        let join_keys = self.on.iter().flat_map(|(left, right)| [left, right]);
        let filter = self.filter.iter().map(|filter| filter.expression());
        crate::apply_expression_roots(join_keys.chain(filter), f)
    }

    fn replace_children(
        self: Arc<Self>,
        mut children: Vec<Arc<dyn ExecutionPlan>>,
        options: ReplaceChildrenOptions,
    ) -> Result<Arc<dyn ExecutionPlan>> {
        validate_child_count!(self, children);
        match options.children_properties {
            ChildrenPropertiesMode::Keep => {
                let left = children.swap_remove(0);
                let right = children.swap_remove(0);
                Ok(Arc::new(Self {
                    left,
                    right,
                    metrics: ExecutionPlanMetricsSet::new(),
                    ..Self::clone(&*self)
                }))
            }
            ChildrenPropertiesMode::Recompute => match &children[..] {
                [left, right] => Ok(Arc::new(
                    SortMergeJoinExec::try_new(
                        Arc::clone(left),
                        Arc::clone(right),
                        self.on.clone(),
                        self.filter.clone(),
                        self.join_type,
                        self.sort_options.clone(),
                        self.null_equality,
                    )?
                    .with_projection(self.projection.clone())?,
                )),
                _ => internal_err!("SortMergeJoin wrong number of children"),
            },
        }
    }

    fn with_new_children(
        self: Arc<Self>,
        children: Vec<Arc<dyn ExecutionPlan>>,
    ) -> Result<Arc<dyn ExecutionPlan>> {
        self.replace_children(
            children,
            ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute),
        )
    }

    fn with_new_children_and_same_properties(
        self: Arc<Self>,
        children: Vec<Arc<dyn ExecutionPlan>>,
    ) -> Result<Arc<dyn ExecutionPlan>> {
        self.replace_children(
            children,
            ReplaceChildrenOptions::new(ChildrenPropertiesMode::Keep),
        )
    }

    fn execute(
        &self,
        partition: usize,
        context: Arc<TaskContext>,
    ) -> Result<SendableRecordBatchStream> {
        let left_partitions = self.left.output_partitioning().partition_count();
        let right_partitions = self.right.output_partitioning().partition_count();
        assert_eq_or_internal_err!(
            left_partitions,
            right_partitions,
            "Invalid SortMergeJoinExec, partition count mismatch {left_partitions}!={right_partitions},\
                 consider using RepartitionExec"
        );
        // execute children plans
        let left = self.left.execute(partition, Arc::clone(&context))?;
        let right = self.right.execute(partition, Arc::clone(&context))?;
        let (on_left, on_right) = self.on.iter().cloned().unzip();

        let joined = sort_merge_join_stream(
            SortMergeJoinInputs {
                schema: Arc::clone(&self.schema),
                sort_options: self.sort_options.clone(),
                null_equality: self.null_equality,
                left,
                right,
                on_left,
                on_right,
                filter: self.filter.clone(),
                join_type: self.join_type,
                partition,
            },
            &self.metrics,
            &context,
        )?;

        let Some(projection) = self.projection.clone() else {
            return Ok(joined);
        };
        let schema = self.schema();
        Ok(Box::pin(RecordBatchStreamAdapter::new(
            Arc::clone(&schema),
            joined.map(move |batch| Ok(batch?.project(&projection)?)),
        )))
    }

    fn metrics(&self) -> Option<MetricsSet> {
        Some(self.metrics.clone_inner())
    }

    fn child_stats_requests(&self, partition: Option<usize>) -> Vec<ChildStats> {
        vec![ChildStats::At(partition), ChildStats::At(partition)]
    }

    fn statistics_from_inputs(
        &self,
        input_stats: &[Arc<Statistics>],
        _args: &StatisticsArgs,
    ) -> Result<Arc<Statistics>> {
        // SortMergeJoinExec uses symmetric hash partitioning where both left and right
        // inputs are hash-partitioned on the join keys. This means partition `i` of the
        // left input is joined with partition `i` of the right input.
        //
        // TODO stats: it is not possible in general to know the output size of joins
        // There are some special cases though, for example:
        // - `A LEFT JOIN B ON A.col=B.col` with `COUNT_DISTINCT(B.col)=COUNT(B.col)`
        let left_stats = input_stats[0].as_ref().clone();
        let right_stats = input_stats[1].as_ref().clone();
        let stats = estimate_join_statistics(
            left_stats,
            right_stats,
            &self.on,
            self.null_equality,
            &self.join_type,
            &self.schema,
        )?;
        Ok(Arc::new(match &self.projection {
            Some(projection) => stats.project(Some(projection)),
            None => stats,
        }))
    }

    /// Tries to push `projection` down through this join. If possible, returns a
    /// new [`SortMergeJoinExec`] whose children are the projected inputs. Otherwise
    /// the join applies the projection itself (see [`EmbeddedProjection`]).
    fn try_swapping_with_projection(
        &self,
        projection: &ProjectionExec,
    ) -> Result<Option<Arc<dyn ExecutionPlan>>> {
        if self.projection.is_some() {
            return Ok(None);
        }

        let schema = self.schema();
        let (_, column_indices) = build_join_schema(
            &self.left().schema(),
            &self.right().schema(),
            &self.join_type,
        );

        // Remaps the join keys and the filter's column indices to the
        // projected children, and declines the pushdown if the projection
        // drops a column the filter needs.
        if let Some(JoinData {
            projected_left_child,
            projected_right_child,
            join_filter,
            join_on,
        }) = try_pushdown_through_join_with_column_indices(
            projection,
            self.left(),
            self.right(),
            self.on(),
            &schema,
            self.filter().as_ref(),
            &column_indices,
        )? {
            Ok(Some(Arc::new(SortMergeJoinExec::try_new(
                Arc::new(projected_left_child),
                Arc::new(projected_right_child),
                join_on,
                join_filter,
                self.join_type,
                self.sort_options.clone(),
                self.null_equality,
            )?)))
        } else {
            try_embed_projection(projection, self)
        }
    }

    #[cfg(feature = "proto")]
    fn try_to_proto(
        &self,
        ctx: &crate::proto::ExecutionPlanEncodeCtx<'_>,
    ) -> Result<Option<datafusion_proto_models::protobuf::PhysicalPlanNode>> {
        use datafusion_proto_models::protobuf;

        // Destructure exhaustively (no `..`) so that a newly added field is a
        // compile error here instead of being silently left out of the proto.
        let Self {
            left,
            right,
            on,
            filter,
            join_type,
            sort_options,
            null_equality,
            projection,
            // derived from the children's schemas by `try_new` on decode
            schema: _,
            // runtime metrics, not part of the plan
            metrics: _,
            // recomputed from `on` and `sort_options` by `try_new` on decode
            left_sort_exprs: _,
            // recomputed from `on` and `sort_options` by `try_new` on decode
            right_sort_exprs: _,
            // recomputed by `try_new` on decode
            cache: _,
        } = self;

        let left = ctx.encode_child(left)?;
        let right = ctx.encode_child(right)?;
        let on = on
            .iter()
            .map(|(left, right)| {
                Ok(protobuf::JoinOn {
                    left: Some(ctx.encode_expr(left)?),
                    right: Some(ctx.encode_expr(right)?),
                })
            })
            .collect::<Result<Vec<_>>>()?;

        let join_type = crate::joins::proto::join_type_to_proto(*join_type);
        let null_equality = crate::joins::proto::null_equality_to_proto(*null_equality);
        let filter = filter
            .as_ref()
            .map(|filter| crate::joins::proto::join_filter_to_proto(filter, ctx))
            .transpose()?;
        let sort_options = sort_options
            .iter()
            .map(|options| protobuf::SortExprNode {
                expr: None,
                asc: !options.descending,
                nulls_first: options.nulls_first,
            })
            .collect();

        Ok(Some(protobuf::PhysicalPlanNode {
            physical_plan_type: Some(
                protobuf::physical_plan_node::PhysicalPlanType::SortMergeJoin(Box::new(
                    protobuf::SortMergeJoinExecNode {
                        left: Some(Box::new(left)),
                        right: Some(Box::new(right)),
                        on,
                        join_type: join_type.into(),
                        filter,
                        sort_options,
                        null_equality: null_equality.into(),
                        // Proto3 `repeated` cannot distinguish `None` from
                        // `Some(vec![])`. `Some(vec![])` (reachable via
                        // `try_embed_projection` for e.g. `SELECT count(1) … JOIN …`)
                        // changes the output schema, so it is encoded with the
                        // single-element sentinel `[u32::MAX]` (never a valid column
                        // index); every other state is sent as-is. See
                        // `try_from_proto` for the matching decoder.
                        projection: match projection.as_ref() {
                            None => Vec::new(),
                            Some(indices) if indices.is_empty() => vec![u32::MAX],
                            Some(indices) => {
                                indices.iter().map(|index| *index as u32).collect()
                            }
                        },
                    },
                )),
            ),
        }))
    }
}

#[cfg(feature = "proto")]
impl SortMergeJoinExec {
    /// Reconstruct a [`SortMergeJoinExec`] from its protobuf representation.
    ///
    /// The exact inverse of [`ExecutionPlan::try_to_proto`].
    ///
    /// [`ExecutionPlan::try_to_proto`]: crate::ExecutionPlan::try_to_proto
    pub fn try_from_proto(
        node: &datafusion_proto_models::protobuf::PhysicalPlanNode,
        ctx: &crate::proto::ExecutionPlanDecodeCtx<'_>,
    ) -> Result<Arc<dyn ExecutionPlan>> {
        use datafusion_proto_models::protobuf;

        let sort_join = crate::expect_plan_variant!(
            node,
            protobuf::physical_plan_node::PhysicalPlanType::SortMergeJoin,
            "SortMergeJoinExec",
        );
        // Destructure exhaustively (no `..`) so that a newly added proto field
        // is a compile error here instead of being silently ignored.
        let protobuf::SortMergeJoinExecNode {
            left,
            right,
            on,
            join_type,
            filter,
            sort_options,
            null_equality,
            projection,
        } = &**sort_join;

        let left =
            ctx.decode_required_child(left.as_deref(), "SortMergeJoinExec", "left")?;
        let right =
            ctx.decode_required_child(right.as_deref(), "SortMergeJoinExec", "right")?;
        let left_schema = left.schema();
        let right_schema = right.schema();
        let on = on
            .iter()
            .map(|columns| {
                let left = ctx.decode_required_expr(
                    columns.left.as_ref(),
                    left_schema.as_ref(),
                    "SortMergeJoinExec",
                    "on.left",
                )?;
                let right = ctx.decode_required_expr(
                    columns.right.as_ref(),
                    right_schema.as_ref(),
                    "SortMergeJoinExec",
                    "on.right",
                )?;
                Ok((left, right))
            })
            .collect::<Result<JoinOn>>()?;

        let join_type =
            crate::joins::proto::join_type_from_proto(*join_type, "SortMergeJoinExec")?;
        let null_equality = crate::joins::proto::null_equality_from_proto(
            *null_equality,
            "SortMergeJoinExec",
        )?;
        let filter = filter
            .as_ref()
            .map(|filter| {
                crate::joins::proto::join_filter_from_proto(
                    filter,
                    ctx,
                    "SortMergeJoinExec",
                )
            })
            .transpose()?;
        let sort_options = sort_options
            .iter()
            .map(|options| SortOptions {
                descending: !options.asc,
                nulls_first: options.nulls_first,
            })
            .collect();

        // Preserve the empty-projection sentinel written by `try_to_proto`.
        let projection = match projection.as_slice() {
            [] => None,
            [u32::MAX] => Some(Vec::new()),
            indices => Some(indices.iter().map(|index| *index as usize).collect()),
        };

        Ok(Arc::new(
            Self::try_new(
                left,
                right,
                on,
                filter,
                join_type,
                sort_options,
                null_equality,
            )?
            .with_projection(projection)?,
        ))
    }
}

/// The two sorted inputs of one partition of a sort-merge join, and how to
/// join them.
pub(crate) struct SortMergeJoinInputs {
    /// The join schema (before any projection)
    pub(crate) schema: SchemaRef,
    /// Sort options of the join keys, one per key, that both inputs are sorted with
    pub(crate) sort_options: Vec<SortOptions>,
    pub(crate) null_equality: NullEquality,
    /// Left input, sorted on `on_left` with `sort_options`
    pub(crate) left: SendableRecordBatchStream,
    /// Right input, sorted on `on_right` with `sort_options`
    pub(crate) right: SendableRecordBatchStream,
    pub(crate) on_left: Vec<PhysicalExprRef>,
    pub(crate) on_right: Vec<PhysicalExprRef>,
    pub(crate) filter: Option<JoinFilter>,
    pub(crate) join_type: JoinType,
    pub(crate) partition: usize,
}

/// Joins two sorted inputs with the sort-merge join algorithm.
///
/// Picks the streamed and buffered side by join type and the join stream
/// implementation by join type family. [`SortMergeJoinExec::execute`] is the
/// only caller today; it is a separate function so that an operator which
/// already holds two sorted streams can reuse it. The stream's metrics are
/// registered in `metrics`; its buffered side spills through the context's
/// disk manager under the memory pool's control.
pub(crate) fn sort_merge_join_stream(
    inputs: SortMergeJoinInputs,
    metrics: &ExecutionPlanMetricsSet,
    context: &Arc<TaskContext>,
) -> Result<SendableRecordBatchStream> {
    let SortMergeJoinInputs {
        schema,
        sort_options,
        null_equality,
        left,
        right,
        on_left,
        on_right,
        filter,
        join_type,
        partition,
    } = inputs;

    let (streamed, buffered, on_streamed, on_buffered) =
        if SortMergeJoinExec::probe_side(&join_type) == JoinSide::Left {
            (left, right, on_left, on_right)
        } else {
            (right, left, on_right, on_left)
        };

    let batch_size = context.session_config().batch_size();
    // The stream spills its buffered batches when it cannot grow, so a
    // pool that budgets spillable and unspillable consumers differently
    // (`FairSpillPool`) has to know it can.
    let reservation = MemoryConsumer::new(format!("SMJStream[{partition}]"))
        .with_can_spill(true)
        .register(context.memory_pool());
    let spill_manager = SpillManager::new(
        context.runtime_env(),
        SpillMetrics::new(metrics, partition),
        buffered.schema(),
    )
    .with_compression_type(context.session_config().spill_compression());

    if matches!(
        join_type,
        JoinType::LeftSemi
            | JoinType::LeftAnti
            | JoinType::RightSemi
            | JoinType::RightAnti
            | JoinType::LeftMark
            | JoinType::RightMark
    ) {
        BitwiseSortMergeJoinStream::try_new(
            schema,
            sort_options,
            null_equality,
            streamed,
            buffered,
            on_streamed,
            on_buffered,
            filter,
            join_type,
            batch_size,
            partition,
            metrics,
            reservation,
            spill_manager,
            context.runtime_env(),
        )
    } else {
        MaterializingSortMergeJoinStream::try_new(
            schema,
            sort_options,
            null_equality,
            streamed,
            buffered,
            on_streamed,
            on_buffered,
            filter,
            join_type,
            batch_size,
            SortMergeJoinMetrics::new(partition, metrics),
            reservation,
            spill_manager,
            context.runtime_env(),
        )
    }
}