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
// 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

//! PiecewiseMergeJoin stream specialized for existence joins.
//!
//! Instantiated by [`PiecewiseMergeJoinExec`] when the join type is `LeftSemi`, `LeftAnti`, or
//! `LeftMark`. `RightSemi`/`RightAnti`/`RightMark` mark the streamed side instead and are
//! served by `RightExistencePWMJStream` (see `right_existence_join.rs`).
//!
//! # Motivation
//!
//! `ClassicPWMJStream` (see `classic_join.rs`) materializes `(buffered, streamed)` row
//! pairs: on the first matching buffered row it emits the whole matching suffix joined
//! with the current streamed row. Existence joins only need a boolean per buffered row —
//! does any match exist? — so pair materialization is pure waste, and the resume state it
//! requires (partial output batches, per-row buffered/streamed cursors) is dead weight.
//!
//! This stream instead records matches as a single index -- the start of the matched
//! suffix -- and emits nothing at all while scanning. Output is produced once, at the end,
//! by slicing the buffered batch at that index.
//!
//! # Algorithm
//!
//! The buffered (left) side arrives globally sorted, enforced by `required_input_ordering`
//! (the streamed side carries no ordering requirement). For a streamed key, a binary search
//! finds the first matching buffered row; because the buffered side is sorted, every buffered
//! row from that position onward matches too:
//!
//! ```text
//!   buffered (sorted):  [1, 3, 5, 7]
//!                           ▲
//!                           first match for this streamed row
//!                           → mark [1..4), i.e. buffered 3, 5, 7
//! ```
//!
//! Marking that suffix covers every match the batch can produce, so only one row of the
//! batch is ever compared against the buffered side: the extreme key, which reaches the
//! smallest matching `buffer_idx`, while every other row matches a subset of that suffix.
//!
//! The search stops at `min_marked`: rows from there on were already marked, by this
//! partition or another, so a match found among them would record nothing. Marking is then a
//! single `fetch_min`, and finding the first match is a binary search, so a batch costs
//! `O(log buffered)` rather than `O(buffered)`.
//!
//! `min_marked` lives in the shared buffered data, so partitions benefit from each other's
//! marking rather than each rediscovering it. It only ever decreases, so a partition that
//! reads a stale value scans a wider range than it had to -- never a narrower one.
//!
//! Once `min_marked` reaches the first non-null buffered row nothing can ever be marked
//! again, and every partition stops reading the streamed side -- checked before each poll,
//! so a partition that starts late reads nothing at all.
//!
//! Rows whose join key is NULL never satisfy a comparison predicate. Buffered NULLs sort to
//! either end, outside the searched range, and null-keyed buffered rows are left unmarked —
//! correctly excluded from `LeftSemi` and included in `LeftAnti`. The extreme key is picked
//! from each streamed batch with NULLs ignored, so it is non-null unless the whole batch is.
//!
//! # Output
//!
//! Marking only ever covers a suffix, and each mark lowers the watermark to its own start,
//! so the matched set is always exactly `[min_marked, non_null_end)`. A bitmap would be a
//! less compact encoding of that one index, so none is allocated. `ClassicPWMJStream` marks
//! the same way, which is why the watermark lives in `BufferedSideData` rather than here.
//!
//! Once every streamed partition has been consumed, the last one to finish slices the
//! buffered batch: `LeftSemi` takes `[min_marked, non_null_end)`, `LeftAnti` the complementary
//! prefix `[0, min_marked)` plus any trailing null-keyed rows. `LeftMark` takes
//! neither slice: every buffered row is preserved, with a `mark` column built from the same
//! watermark (`true` in the matched range, `false` elsewhere) appended instead of any row
//! being dropped. Only the buffered (left) columns, plus that `mark` column for `LeftMark`,
//! are produced.
//!
//! [`PiecewiseMergeJoinExec`]: super::PiecewiseMergeJoinExec

use std::cmp::Ordering;
use std::sync::Arc;
use std::sync::atomic::Ordering as AtomicOrdering;
use std::task::{Poll, ready};

use arrow::array::{
    Array, ArrayRef, BooleanArray, BooleanBufferBuilder, RecordBatch, UInt32Array,
    new_null_array,
};
use arrow::compute::{BatchCoalescer, take};
use arrow_ord::ord::make_comparator;
use arrow_schema::{SchemaRef, SortOptions};
use datafusion_common::{NullEquality, Result, internal_err};
use datafusion_execution::{RecordBatchStream, SendableRecordBatchStream};
use datafusion_expr::{JoinType, Operator};
use datafusion_functions_aggregate_common::min_max::{max_batch, min_batch};
use datafusion_physical_expr::PhysicalExprRef;
use futures::{Stream, StreamExt};

use super::utils::{non_null_range, unmatched_buffered_batch};
use crate::handle_state;
use crate::joins::piecewise_merge_join::exec::{BufferedSide, BufferedSideReadyState};
use crate::joins::piecewise_merge_join::utils::{
    first_match, is_match, matches_on_equal,
};
use crate::joins::utils::{
    BuildProbeJoinMetrics, JoinKeyComparator, StatefulStreamResult,
};
use crate::stream::EmptyRecordBatchStream;

pub(super) enum ExistencePWMJStreamState {
    /// Load the buffered side into memory.
    WaitBufferedSide,
    /// Fetch and scan streamed batches, lowering the watermark. Emits nothing.
    ScanStreamBatches,
    /// Emit the result. Reached only by the last streamed partition.
    EmitMatched,
    Completed,
}

pub(super) struct ExistencePWMJStream {
    /// Output schema, which for `LeftSemi`/`LeftAnti` is the buffered side's schema, and for
    /// `LeftMark` is that schema plus a trailing `mark` column
    schema: SchemaRef,
    /// Physical expression evaluated on the streamed side. The buffered side's
    /// equivalent is already evaluated when the buffered side is collected.
    on_streamed: PhysicalExprRef,
    /// `LeftSemi`, `LeftAnti`, or `LeftMark`
    join_type: JoinType,
    /// Comparison operator
    operator: Operator,
    streamed: SendableRecordBatchStream,
    buffered_side: BufferedSide,
    state: ExistencePWMJStreamState,
    /// Whether the buffered side is sorted ascending or descending, per the operator
    sort_option: SortOptions,
    join_metrics: BuildProbeJoinMetrics,
    /// Chunks the single final-pass batch to `batch_size`
    output_batches: Box<BatchCoalescer>,
    /// Whether the final pass has already pushed its result into `output_batches`
    emitted: bool,
}

impl ExistencePWMJStream {
    #[expect(clippy::too_many_arguments)]
    pub(super) fn try_new(
        schema: SchemaRef,
        on_streamed: PhysicalExprRef,
        join_type: JoinType,
        operator: Operator,
        streamed: SendableRecordBatchStream,
        buffered_side: BufferedSide,
        sort_option: SortOptions,
        join_metrics: BuildProbeJoinMetrics,
        batch_size: usize,
    ) -> Self {
        Self {
            output_batches: Box::new(BatchCoalescer::new(
                Arc::clone(&schema),
                batch_size,
            )),
            schema,
            on_streamed,
            join_type,
            operator,
            streamed,
            buffered_side,
            state: ExistencePWMJStreamState::WaitBufferedSide,
            sort_option,
            join_metrics,
            emitted: false,
        }
    }

    fn poll_next_impl(
        &mut self,
        cx: &mut std::task::Context<'_>,
    ) -> Poll<Option<Result<RecordBatch>>> {
        loop {
            return match self.state {
                ExistencePWMJStreamState::WaitBufferedSide => {
                    handle_state!(ready!(self.collect_buffered_side(cx)))
                }
                ExistencePWMJStreamState::ScanStreamBatches => {
                    handle_state!(ready!(self.scan_stream_batch(cx)))
                }
                ExistencePWMJStreamState::EmitMatched => {
                    handle_state!(self.emit_matched())
                }
                ExistencePWMJStreamState::Completed => Poll::Ready(None),
            };
        }
    }

    /// Collects the buffered side into memory.
    fn collect_buffered_side(
        &mut self,
        cx: &mut std::task::Context<'_>,
    ) -> Poll<Result<StatefulStreamResult<Option<RecordBatch>>>> {
        let build_timer = self.join_metrics.build_time.timer();
        let buffered_data = ready!(
            self.buffered_side
                .try_as_initial_mut()?
                .buffered_fut
                .get_shared(cx)
        )?;
        build_timer.done();

        self.buffered_side =
            BufferedSide::Ready(BufferedSideReadyState { buffered_data });
        self.state = ExistencePWMJStreamState::ScanStreamBatches;

        Poll::Ready(Ok(StatefulStreamResult::Continue))
    }

    /// Fetches one streamed batch, reduces it to its extreme compare key, and marks the
    /// buffered rows that key matches.
    /// Never produces output: existence results come from the watermark in `emit_matched`.
    fn scan_stream_batch(
        &mut self,
        cx: &mut std::task::Context<'_>,
    ) -> Poll<Result<StatefulStreamResult<Option<RecordBatch>>>> {
        // Every buffered row that can ever be marked is already marked -- by this
        // partition or any other, since the watermark is shared -- so no batch can lower
        // the watermark further. Stop reading rather than scanning batches that provably
        // cannot contribute. Checked before polling so a partition that starts after another
        // has saturated the watermark reads nothing at all.
        if self.nothing_left_to_mark()? {
            self.finish_streamed_side()?;
            return Poll::Ready(Ok(StatefulStreamResult::Continue));
        }

        let next_batch = ready!(self.streamed.poll_next_unpin(cx));
        let join_time = self.join_metrics.join_time.clone();
        let _join_timer = join_time.timer();
        match next_batch {
            None => self.finish_streamed_side()?,
            Some(Ok(batch)) => {
                let stream_values: ArrayRef = self
                    .on_streamed
                    .evaluate(&batch)?
                    .into_array(batch.num_rows())?;

                self.join_metrics.input_batches.add(1);
                self.join_metrics.input_rows.add(batch.num_rows());

                // Only the batch's extreme key is ever compared against the buffered side,
                // so reduce the batch to that one key.
                let stream_values =
                    extreme_key(&stream_values, self.sort_option.descending)?;

                self.mark_matched_buffered_rows(&stream_values)?;
            }
            Some(Err(err)) => return Poll::Ready(Err(err)),
        }

        Poll::Ready(Ok(StatefulStreamResult::Continue))
    }

    /// Whether no buffered row can ever be marked again, in which case the streamed side
    /// no longer needs reading. Reads the shared watermark, so one partition saturating it
    /// lets every other partition stop too.
    fn nothing_left_to_mark(&self) -> Result<bool> {
        let buffered_data = &self.buffered_side.try_as_ready()?.buffered_data;
        let min_marked = buffered_data.min_marked.load(AtomicOrdering::SeqCst);
        let buffered_values = buffered_data.values();

        let (start, end) = non_null_range(buffered_values.as_ref(), self.sort_option);
        Ok(min_marked.min(end) <= start)
    }

    /// Marks this partition done with the streamed side: releases the input pipeline and,
    /// if this is the last streamed partition to finish, moves on to the final pass.
    fn finish_streamed_side(&mut self) -> Result<()> {
        // Release the streamed input pipeline's resources.
        let streamed_schema = self.streamed.schema();
        self.streamed = Box::pin(EmptyRecordBatchStream::new(streamed_schema));

        // The final pass must run exactly once, on the last streamed partition to finish.
        if self
            .buffered_side
            .try_as_ready()?
            .buffered_data
            .remaining_partitions
            .fetch_sub(1, AtomicOrdering::SeqCst)
            == 1
        {
            self.state = ExistencePWMJStreamState::EmitMatched;
        } else {
            self.state = ExistencePWMJStreamState::Completed;
        }

        Ok(())
    }

    /// Marks every buffered row matched by `stream_values`, a one-row array holding the
    /// batch's extreme compare key (null only if the whole batch was null).
    fn mark_matched_buffered_rows(&mut self, stream_values: &ArrayRef) -> Result<()> {
        let operator = self.operator;
        let sort_option = self.sort_option;

        {
            let buffered_data = &self.buffered_side.try_as_ready()?.buffered_data;
            let buffered_values = buffered_data.values();

            let (first_non_null_buffered, non_null_end) =
                non_null_range(buffered_values.as_ref(), sort_option);

            // `[min_marked, non_null_end)` was already marked, by this partition or
            // another, so a match found there would write nothing. Stop the scan at the
            // watermark: that bounds the comparisons this batch performs, not just the
            // bits it writes.
            let scan_limit = buffered_data
                .min_marked
                .load(AtomicOrdering::SeqCst)
                .min(non_null_end);

            // The extreme key is the only one that can decide anything: it reaches the
            // smallest matching `buffer_idx`, and every other row in the batch matches a
            // subset of the same buffered suffix, so could only re-mark it. `null_count()`
            // is 0 for a real key and 1 for an all-null batch, which skips the scan.
            let row_idx = stream_values.null_count();

            // Validated once here rather than inside the search below.
            let match_on_equal = matches_on_equal(operator)?;

            if row_idx < stream_values.len() && first_non_null_buffered < scan_limit {
                let cmp = JoinKeyComparator::new(
                    &[Arc::clone(stream_values)],
                    &[Arc::clone(buffered_values)],
                    &[sort_option],
                    NullEquality::NullEqualsNothing,
                )?;
                let matches = |buffer_idx: usize| {
                    is_match(cmp.compare(row_idx, buffer_idx), match_on_equal)
                };

                // Because the buffered side is sorted, `matches` is monotone over it:
                // false while the buffered key has not yet passed the streamed key, true
                // from there on. `buffer_idx` is the first matching buffered index, or
                // `scan_limit` if this batch matches nothing new.
                let buffer_idx =
                    first_match(first_non_null_buffered, scan_limit, matches);
                if buffer_idx < scan_limit {
                    // Everything from `buffer_idx` on matches, so lowering the
                    // watermark to it records the match: the marked set is exactly
                    // `[min_marked, non_null_end)` and needs no bitmap.
                    //
                    // INVARIANT: sound only because the buffered side and each
                    // streamed batch are sorted the same way for this operator
                    // (`try_new` derives `sort_option`: descending for `<`/`<=`,
                    // ascending for `>`/`>=`). That makes this the smallest reachable
                    // `buffer_idx`, so the marked suffix is maximal. Only the ordering
                    // *within* a batch matters; batches themselves may arrive in any
                    // order, which is why the watermark takes a `min` rather than just
                    // decreasing.
                    buffered_data
                        .min_marked
                        .fetch_min(buffer_idx, AtomicOrdering::SeqCst);
                }
            }
        }

        Ok(())
    }

    /// Emits the existence result by slicing at the watermark: the marked buffered rows for
    /// `LeftSemi`, the unmarked ones for `LeftAnti`, or -- for `LeftMark` -- every buffered row
    /// with a `mark` column built from the same watermark.
    fn emit_matched(&mut self) -> Result<StatefulStreamResult<Option<RecordBatch>>> {
        let _join_timer = self.join_metrics.join_time.timer();
        if !self.emitted {
            self.emitted = true;

            let buffered_data =
                Arc::clone(&self.buffered_side.try_as_ready()?.buffered_data);
            let buffered_batch = buffered_data.batch();
            let buffered_len = buffered_batch.num_rows();

            // The matched non-null suffix is `[min_marked, non_null_end)`.
            // Each match lowers the watermark; trailing NULL keys stay unmarked.
            let (_, non_null_end) =
                non_null_range(buffered_data.values().as_ref(), self.sort_option);
            let min_marked = buffered_data
                .min_marked
                .load(AtomicOrdering::SeqCst)
                .min(non_null_end);

            let (num_rows, columns) = match self.join_type {
                JoinType::LeftSemi => {
                    let sliced =
                        buffered_batch.slice(min_marked, non_null_end - min_marked);
                    (sliced.num_rows(), sliced.columns().to_vec())
                }
                // `LeftMark` keeps every buffered row -- nothing to slice -- and appends
                // the watermark as a `mark` column: true only within the matched
                // non-null range, false for the prefix and any trailing NULL keys.
                JoinType::LeftMark => {
                    let mut mark = BooleanBufferBuilder::new(buffered_len);
                    mark.append_n(min_marked, false);
                    mark.append_n(non_null_end - min_marked, true);
                    mark.append_n(buffered_len - non_null_end, false);

                    let mut columns = buffered_batch.columns().to_vec();
                    columns.push(
                        Arc::new(BooleanArray::new(mark.finish(), None)) as ArrayRef
                    );
                    (buffered_len, columns)
                }
                // `LeftAnti` includes the unmarked prefix and any trailing NULL keys.
                JoinType::LeftAnti => {
                    let sliced = unmatched_buffered_batch(
                        buffered_batch,
                        min_marked,
                        non_null_end,
                    )?;
                    (sliced.num_rows(), sliced.columns().to_vec())
                }
                other => {
                    return internal_err!(
                        "ExistencePWMJStream does not support join type {other:?}"
                    );
                }
            };

            if num_rows > 0 {
                // Existence joins output the buffered (left) columns only (plus `mark` for
                // `LeftMark`); rebuild against the join's own schema, which keeps a slice
                // zero-copy.
                let batch = RecordBatch::try_new(Arc::clone(&self.schema), columns)?;
                self.output_batches.push_batch(batch)?;
                self.output_batches.finish_buffered_batch()?;
            }
        }

        // Drain one coalesced batch per poll; `emitted` keeps the block above from
        // re-running, so this always terminates.
        match self.output_batches.next_completed_batch() {
            Some(batch) => Ok(StatefulStreamResult::Ready(Some(batch))),
            None => {
                self.state = ExistencePWMJStreamState::Completed;
                Ok(StatefulStreamResult::Ready(None))
            }
        }
    }
}

/// Reduces `values` to a one-row array holding the batch's extreme compare key: the maximum
/// when the batch's sort is `descending`, the minimum otherwise. Nulls are ignored, so that
/// row is null only when every key in the batch is (or the batch is empty), which marks
/// nothing.
///
/// Ordered the same way as [`JoinKeyComparator`]: both use IEEE 754 totalOrder for floats,
/// and the comparator normalizes `-0.0` on either side of it.
///
/// Nested keys use Arrow's comparator, so inner NULLs have the same ordering as
/// sorting and range comparisons. Other keys use the typed min/max kernels.
pub(super) fn extreme_key(values: &ArrayRef, descending: bool) -> Result<ArrayRef> {
    if values.data_type().is_nested() {
        // Reverse both value and inner-NULL ordering for max, matching SQL's
        // ascending NULLS FIRST nested comparison order.
        let cmp = make_comparator(
            values.as_ref(),
            values.as_ref(),
            SortOptions::new(descending, !descending),
        )?;
        let nulls = values.logical_nulls();
        let mut extreme = None;
        for idx in 0..values.len() {
            if nulls.as_ref().is_some_and(|n| n.is_null(idx)) {
                continue;
            }
            if extreme.is_none_or(|current| cmp(idx, current) == Ordering::Less) {
                extreme = Some(idx);
            }
        }
        return match extreme {
            Some(idx) => Ok(take(
                values.as_ref(),
                &UInt32Array::from(vec![idx as u32]),
                None,
            )?),
            None => Ok(new_null_array(values.data_type(), 1)),
        };
    }
    let extreme = if descending {
        max_batch(values)?
    } else {
        min_batch(values)?
    };
    extreme.to_array_of_size(1)
}

impl RecordBatchStream for ExistencePWMJStream {
    fn schema(&self) -> SchemaRef {
        Arc::clone(&self.schema)
    }
}

impl Stream for ExistencePWMJStream {
    type Item = Result<RecordBatch>;

    fn poll_next(
        mut self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> Poll<Option<Self::Item>> {
        // `record_poll` fills in `output_rows` and `end_time`; `elapsed_compute` is handled
        // by `BuildProbeJoinMetrics::drop`.
        let poll = self.poll_next_impl(cx);
        self.join_metrics.baseline.record_poll(poll)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        ExecutionPlan, common,
        joins::PiecewiseMergeJoinExec,
        test::{TestMemoryExec, assert_join_metrics, build_table_i32},
    };
    use arrow_schema::{DataType, Field, Schema};
    use datafusion_common::test_util::batches_to_string;
    use datafusion_execution::TaskContext;
    use datafusion_execution::config::SessionConfig;
    use datafusion_physical_expr::expressions::Column;
    use insta::assert_snapshot;

    // Coverage for existence joins lives in `pwmj.slt`: operators, NULL handling, empty
    // sides, key types, both correlation orientations, and the streamed-side batch and
    // partition layouts (which SQL pins via one `INSERT` per batch plus an `EXPLAIN`
    // asserting `partition_sizes`). The two tests here are demos of the operator itself.

    fn build_table(
        a: (&str, &Vec<i32>),
        b: (&str, &Vec<i32>),
        c: (&str, &Vec<i32>),
    ) -> Arc<dyn ExecutionPlan> {
        let batch = build_table_i32(a, b, c);
        let schema = batch.schema();
        TestMemoryExec::try_new_exec(&[vec![batch]], schema, None).unwrap()
    }

    async fn join_collect(join_type: JoinType) -> Result<Vec<RecordBatch>> {
        // Buffered (left) side pre-sorted ascending, as `>` requires. These tests build
        // the exec directly, so there is no `SortExec` to enforce it.
        let left = build_table(
            ("a1", &vec![1, 2, 3]),
            ("b1", &vec![1, 2, 5]),
            ("c1", &vec![7, 8, 9]),
        );
        let right = build_table(
            ("a2", &vec![10, 20, 30]),
            ("b1", &vec![2, 3, 4]),
            ("c2", &vec![70, 80, 90]),
        );
        let on = (
            Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("b1", &right.schema())?) as _,
        );
        let join =
            PiecewiseMergeJoinExec::try_new(left, right, on, Operator::Gt, join_type, 1)?;

        let stream = join.execute(0, Arc::new(TaskContext::default()))?;
        common::collect(stream).await
    }

    /// `LeftSemi` keeps the buffered rows with at least one match, and outputs only the
    /// buffered columns. Of b1 = {1,2,5} against streamed {2,3,4}, only 5 > some streamed
    /// value.
    #[tokio::test]
    async fn join_left_semi() -> Result<()> {
        let batches = join_collect(JoinType::LeftSemi).await?;

        assert_snapshot!(batches_to_string(&batches), @r"
        +----+----+----+
        | a1 | b1 | c1 |
        +----+----+----+
        | 3  | 5  | 9  |
        +----+----+----+
        ");
        Ok(())
    }

    /// `LeftAnti` is the complement: the buffered rows with no match.
    #[tokio::test]
    async fn join_left_anti() -> Result<()> {
        let batches = join_collect(JoinType::LeftAnti).await?;

        assert_snapshot!(batches_to_string(&batches), @r"
        +----+----+----+
        | a1 | b1 | c1 |
        +----+----+----+
        | 1  | 1  | 7  |
        | 2  | 2  | 8  |
        +----+----+----+
        ");
        Ok(())
    }

    /// `LeftMark` keeps every buffered row -- unlike `LeftSemi`/`LeftAnti`, neither is
    /// dropped -- and appends a `mark` column: `true` for exactly the rows `LeftSemi` would
    /// have kept.
    #[tokio::test]
    async fn join_left_mark() -> Result<()> {
        let batches = join_collect(JoinType::LeftMark).await?;

        assert_snapshot!(batches_to_string(&batches), @r"
        +----+----+----+-------+
        | a1 | b1 | c1 | mark  |
        +----+----+----+-------+
        | 1  | 1  | 7  | false |
        | 2  | 2  | 8  | false |
        | 3  | 5  | 9  | true  |
        +----+----+----+-------+
        ");
        Ok(())
    }

    /// Once every markable buffered row is marked, no later streamed batch can lower the
    /// watermark, so the stream stops reading rather than scanning batches that provably
    /// cannot contribute. The first batch below is smaller than every buffered value, so it
    /// marks all four rows; the two batches after it must never be read. Asserted through
    /// the `input_batches` metric, which SQL cannot observe.
    #[tokio::test]
    async fn early_exit_stops_reading_streamed_batches() -> Result<()> {
        let left = build_table(
            ("a1", &vec![1, 2, 3, 4]),
            ("b1", &vec![1, 3, 5, 7]),
            ("c1", &vec![10, 20, 30, 40]),
        );

        let streamed_schema = Schema::new(vec![
            Field::new("a2", DataType::Int32, false),
            Field::new("b1", DataType::Int32, false),
            Field::new("c2", DataType::Int32, false),
        ]);
        // b1=0 is below every buffered value, so batch 1 marks the whole buffered side.
        let batch1 =
            build_table_i32(("a2", &vec![10]), ("b1", &vec![0]), ("c2", &vec![70]));
        let batch2 =
            build_table_i32(("a2", &vec![20]), ("b1", &vec![2]), ("c2", &vec![80]));
        let batch3 =
            build_table_i32(("a2", &vec![30]), ("b1", &vec![6]), ("c2", &vec![90]));
        let right = TestMemoryExec::try_new_exec(
            &[vec![batch1, batch2, batch3]],
            Arc::new(streamed_schema),
            None,
        )?;

        let on = (
            Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("b1", &right.schema())?) as _,
        );
        let join = PiecewiseMergeJoinExec::try_new(
            left,
            right,
            on,
            Operator::Gt,
            JoinType::LeftSemi,
            1,
        )?;

        let stream = join.execute(0, Arc::new(TaskContext::default()))?;
        let batches = common::collect(stream).await?;

        // All four buffered rows still come out.
        assert_snapshot!(batches_to_string(&batches), @r"
        +----+----+----+
        | a1 | b1 | c1 |
        +----+----+----+
        | 1  | 1  | 10 |
        | 2  | 3  | 20 |
        | 3  | 5  | 30 |
        | 4  | 7  | 40 |
        +----+----+----+
        ");

        // ...but only the first of the three streamed batches was ever read.
        let consumed = join
            .metrics()
            .unwrap()
            .sum_by_name("input_batches")
            .expect("input_batches metric")
            .as_usize();
        assert_eq!(consumed, 1, "expected early exit after the first batch");
        Ok(())
    }

    /// The final pass pushes one slice of the buffered batch into a `BatchCoalescer`, so a
    /// result wider than `batch_size` has to be drained over several polls. Also pins the
    /// `output_rows` metric, which `record_poll` in `poll_next` is what supplies, and
    /// `join_time`, which the streamed-side scan and the final pass record.
    #[tokio::test]
    async fn final_pass_chunks_output_and_records_output_rows() -> Result<()> {
        let left = build_table(
            ("a1", &vec![1, 2, 3, 4]),
            ("b1", &vec![1, 3, 5, 7]),
            ("c1", &vec![10, 20, 30, 40]),
        );

        let streamed_schema = Schema::new(vec![
            Field::new("a2", DataType::Int32, false),
            Field::new("b1", DataType::Int32, false),
            Field::new("c2", DataType::Int32, false),
        ]);
        // b1=0 is below every buffered value, so every buffered row matches `>`.
        let batch =
            build_table_i32(("a2", &vec![10]), ("b1", &vec![0]), ("c2", &vec![70]));
        let right = TestMemoryExec::try_new_exec(
            &[vec![batch]],
            Arc::new(streamed_schema),
            None,
        )?;

        let on = (
            Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("b1", &right.schema())?) as _,
        );
        let join = PiecewiseMergeJoinExec::try_new(
            left,
            right,
            on,
            Operator::Gt,
            JoinType::LeftSemi,
            1,
        )?;

        // batch_size 2 over a 4-row result forces the coalescer to hand back two batches.
        let task_ctx = Arc::new(
            TaskContext::default()
                .with_session_config(SessionConfig::new().with_batch_size(2)),
        );
        let stream = join.execute(0, task_ctx)?;
        let batches = common::collect(stream).await?;

        assert_eq!(batches.len(), 2, "expected the final pass to be chunked");
        assert_eq!(batches.iter().map(|b| b.num_rows()).sum::<usize>(), 4);

        let metrics = join.metrics().expect("metrics should be available");
        assert_join_metrics!(metrics, 4);
        assert!(
            metrics
                .sum_by_name("join_time")
                .expect("join_time metric")
                .as_usize()
                > 0
        );
        Ok(())
    }

    /// The watermark lives in the shared buffered data, so one partition saturating it
    /// lets the others stop too. Partition 0's single batch marks every buffered row;
    /// partition 1 is then driven and must read none of its three batches. Only the shared
    /// watermark makes that possible -- with a per-partition watermark, partition 1 would
    /// rescan all three.
    #[tokio::test]
    async fn early_exit_is_shared_across_streamed_partitions() -> Result<()> {
        let left = build_table(
            ("a1", &vec![1, 2, 3, 4]),
            ("b1", &vec![1, 3, 5, 7]),
            ("c1", &vec![10, 20, 30, 40]),
        );

        let streamed_schema = Schema::new(vec![
            Field::new("a2", DataType::Int32, false),
            Field::new("b1", DataType::Int32, false),
            Field::new("c2", DataType::Int32, false),
        ]);
        // Partition 0: one batch below every buffered value -> marks the whole buffered side.
        let p0 = build_table_i32(("a2", &vec![10]), ("b1", &vec![0]), ("c2", &vec![70]));
        // Partition 1: three batches that can now contribute nothing.
        let p1_b0 =
            build_table_i32(("a2", &vec![20]), ("b1", &vec![2]), ("c2", &vec![80]));
        let p1_b1 =
            build_table_i32(("a2", &vec![30]), ("b1", &vec![4]), ("c2", &vec![90]));
        let p1_b2 =
            build_table_i32(("a2", &vec![40]), ("b1", &vec![6]), ("c2", &vec![100]));
        let right = TestMemoryExec::try_new_exec(
            &[vec![p0], vec![p1_b0, p1_b1, p1_b2]],
            Arc::new(streamed_schema),
            None,
        )?;

        let on = (
            Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("b1", &right.schema())?) as _,
        );
        let join = PiecewiseMergeJoinExec::try_new(
            left,
            right,
            on,
            Operator::Gt,
            JoinType::LeftSemi,
            2,
        )?;

        // Driven in order so partition 0 saturates the watermark before partition 1 starts.
        let task_ctx = Arc::new(TaskContext::default());
        let mut batches = Vec::new();
        for partition in 0..2 {
            let stream = join.execute(partition, Arc::clone(&task_ctx))?;
            batches.extend(common::collect(stream).await?);
        }
        let out = arrow::compute::concat_batches(&join.schema(), batches.iter())?;

        assert_snapshot!(batches_to_string(&[out]), @r"
        +----+----+----+
        | a1 | b1 | c1 |
        +----+----+----+
        | 1  | 1  | 10 |
        | 2  | 3  | 20 |
        | 3  | 5  | 30 |
        | 4  | 7  | 40 |
        +----+----+----+
        ");

        // Partition 0 read its one batch; partition 1 read none of its three.
        let consumed = join
            .metrics()
            .unwrap()
            .sum_by_name("input_batches")
            .expect("input_batches metric")
            .as_usize();
        assert_eq!(consumed, 1, "partition 1 should not have read any batch");
        Ok(())
    }
}