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
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
// 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 right existence joins.
//!
//! Instantiated by [`PiecewiseMergeJoinExec`] when the join type is `RightSemi`, `RightAnti`,
//! or `RightMark`. `LeftSemi`/`LeftAnti`/`LeftMark` are served by `ExistencePWMJStream` (see
//! `existence_join.rs`).
//!
//! # Algorithm
//!
//! Left and right existence joins mark opposite sides, and for a single range predicate
//! that difference is not symmetric — it collapses the work.
//!
//! `LeftSemi`/`LeftAnti`/`LeftMark` ask, for each *buffered* row, whether any streamed row
//! matches, so the answer depends on the whole streamed side and can only be emitted once it
//! has all been read. `RightSemi`/`RightAnti`/`RightMark` ask the mirror question — for each
//! *streamed* row, does any buffered row match? — and with only `buffered_key OP
//! streamed_key` to satisfy, that is decided by a single buffered key:
//!
//! ```text
//!   ∃b. b <  s   ⟺   min(b) <  s          ∃b. b >  s   ⟺   max(b) >  s
//!   ∃b. b <= s   ⟺   min(b) <= s          ∃b. b >= s   ⟺   max(b) >= s
//! ```
//!
//! The buffered side is therefore reduced to that one key -- `min_batch`/`max_batch`, folded
//! batch by batch as it streams in -- and each batch is dropped once folded. It is never
//! concatenated or retained, so the state this join holds is a single row however large that
//! side is. The reduction is shared, so every streamed partition reads the same key rather
//! than repeating the pass:
//!
//! ```text
//!   operator `<`, buffered keys [NULL, 5, 9, 7]  ->  min = 5
//!   `b < s` holds for some b   iff   `5 < s`
//! ```
//!
//! A min/max is `O(B)` from any order, so `required_input_ordering` returns nothing for either
//! child and no `SortExec` is planned.
//!
//! Every streamed row is then decided by comparing it against that one key, which is a
//! vectorized `cmp` kernel per batch, followed by a filter (`RightSemi`/`RightAnti`) or a
//! `mark` column appended to the batch unfiltered (`RightMark`). Nothing about a streamed row
//! depends on any other, so:
//!
//! * output is produced per batch as it arrives — no watermark, no final pass, and no
//!   election among the streamed partitions,
//! * all N streamed partitions produce output, rather than one non-empty partition,
//! * the streamed side is never sorted, not even per batch.
//!
//! Rows whose join key is NULL never satisfy a comparison predicate. `min_batch`/`max_batch`
//! ignore NULLs, so the reduced key is null only when *every* buffered key is (or the buffered
//! side is empty) — and then no streamed row can match at all, which makes `RightSemi` empty
//! without reading the streamed side, and `RightAnti`/`RightMark` a passthrough of it (`mark`
//! false on every row for the latter). A NULL streamed key makes its comparison NULL rather
//! than false, which is "no match" — dropped by `RightSemi`, kept by `RightAnti`, and folded
//! to `false` rather than left NULL for `RightMark`, matching the `mark` column's documented
//! never-NULL semantics (see `JoinType::LeftMark`).
//!
//! Picking the extreme and comparing against it must agree on ordering. `min_batch`/`max_batch`
//! order floats by `total_cmp` (`arrow-arith`'s `MinAccumulator` compares with
//! `ArrowNativeTypeOp::is_lt`, seeded from `MAX_TOTAL_ORDER`), which puts `-0.0` strictly below
//! `+0.0` -- but SQL comparisons treat them as equal, and that is what a real `k < r` predicate
//! actually evaluates to: any `BinaryExpr` comparison, including the one the
//! `NestedLoopJoinExec` oracle in the differential fuzz test builds its filter from, normalizes
//! `-0.0` to `+0.0` first (see `apply_cmp` in `datafusion-physical-expr-common`, which
//! [`matched_mask`](RightExistencePWMJStream::matched_mask) calls to compare the extreme
//! against each streamed batch). `apply_cmp` normalizes both operands itself, so nothing here
//! has to: the reduction can order `-0.0` below `+0.0` as `min`/`max` do, and the comparison it
//! feeds into still agrees with SQL semantics. `NaN` needs no such fix-up: every kernel involved
//! orders it as the maximum, so it is treated identically on both sides already. `apply_cmp`
//! also dispatches to the nested-aware comparator for List/Struct keys, which the raw arrow
//! `lt`/`lt_eq`/`gt`/`gt_eq` kernels reject outright.
//!
//! # Cost
//!
//! Let `B` be the buffered rows and `S` the streamed rows: `O(B)` to reduce the buffered side
//! plus `O(S)` to filter, and no sort on either side. The state retained across batches is one
//! row; while folding, each buffered partition also holds the key array of the batch it is
//! reducing, which it accounts against the memory pool for that long.
//!
//! This is why the shared state is [`BufferedExtreme`] and not `BufferedSideData`: every field
//! of the latter -- the concatenated batch, the key array, the visited-indices bitmap, the
//! final-pass counter -- would be dead here.
//!
//! [`PiecewiseMergeJoinExec`]: super::PiecewiseMergeJoinExec

use std::sync::Arc;
use std::task::{Poll, ready};

use arrow::array::{ArrayRef, AsArray, BooleanArray, RecordBatch};
use arrow::buffer::BooleanBuffer;
use arrow::compute::BatchCoalescer;
use arrow::compute::filter_record_batch;
use arrow::compute::kernels::boolean::not;
use arrow_schema::SchemaRef;
use datafusion_common::{Result, ScalarValue};
use datafusion_execution::{RecordBatchStream, SendableRecordBatchStream};
use datafusion_expr::{ColumnarValue, JoinType, Operator};
use datafusion_physical_expr::PhysicalExprRef;
use datafusion_physical_expr_common::datum::apply_cmp;
use futures::{Stream, StreamExt};

use crate::handle_state;
use crate::joins::piecewise_merge_join::exec::BufferedExtreme;
use crate::joins::utils::{
    BuildProbeJoinMetrics, OnceFut, StatefulStreamResult, boolean_mask_from_filter,
};
use crate::stream::EmptyRecordBatchStream;

pub(super) enum RightExistencePWMJStreamState {
    /// Await the buffered side's reduction to a single key.
    WaitBufferedExtreme,
    /// Fetch streamed batches and emit the rows that do (`RightSemi`) or do not
    /// (`RightAnti`) have a buffered match, or every row with `mark` appended (`RightMark`).
    ScanStreamBatches,
    /// Streamed side exhausted; drain whatever `output_batches` still holds.
    Draining,
    Completed,
}

pub(super) struct RightExistencePWMJStream {
    /// Output schema, which for `RightSemi`/`RightAnti` is the streamed side's schema, and for
    /// `RightMark` 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,
    /// `RightSemi`, `RightAnti`, or `RightMark`
    join_type: JoinType,
    /// Comparison operator
    operator: Operator,
    streamed: SendableRecordBatchStream,
    /// Resolves to the whole buffered side reduced to one key. Shared with the other streamed
    /// partitions, so that reduction happens exactly once.
    buffered_extreme_fut: OnceFut<BufferedExtreme>,
    state: RightExistencePWMJStreamState,
    /// That key, held as a [`ScalarValue`] so `apply_cmp` broadcasts it against a streamed
    /// batch in one call. `None` when the buffered side has no non-null key, i.e. nothing can
    /// ever match. Only populated once `buffered_extreme_fut` has resolved.
    buffered_extreme: Option<ScalarValue>,
    join_metrics: BuildProbeJoinMetrics,
    /// Chunks the per-streamed-batch output to `batch_size`, so a low-selectivity join
    /// does not hand downstream operators one small batch per streamed batch.
    output_batches: Box<BatchCoalescer>,
}

impl RightExistencePWMJStream {
    #[expect(clippy::too_many_arguments)]
    pub(super) fn try_new(
        schema: SchemaRef,
        on_streamed: PhysicalExprRef,
        join_type: JoinType,
        operator: Operator,
        streamed: SendableRecordBatchStream,
        buffered_extreme_fut: OnceFut<BufferedExtreme>,
        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_extreme_fut,
            state: RightExistencePWMJStreamState::WaitBufferedExtreme,
            buffered_extreme: None,
            join_metrics,
        }
    }

    fn poll_next_impl(
        &mut self,
        cx: &mut std::task::Context<'_>,
    ) -> Poll<Option<Result<RecordBatch>>> {
        loop {
            return match self.state {
                RightExistencePWMJStreamState::WaitBufferedExtreme => {
                    handle_state!(ready!(self.collect_buffered_extreme(cx)))
                }
                RightExistencePWMJStreamState::ScanStreamBatches => {
                    handle_state!(ready!(self.scan_stream_batch(cx)))
                }
                RightExistencePWMJStreamState::Draining => {
                    handle_state!(self.drain_output())
                }
                RightExistencePWMJStreamState::Completed => Poll::Ready(None),
            };
        }
    }

    /// Picks up the buffered side's reduced key, which is all this join type needs from it.
    fn collect_buffered_extreme(
        &mut self,
        cx: &mut std::task::Context<'_>,
    ) -> Poll<Result<StatefulStreamResult<Option<RecordBatch>>>> {
        let build_timer = self.join_metrics.build_time.timer();
        let buffered_extreme = ready!(self.buffered_extreme_fut.get_shared(cx))?;
        build_timer.done();

        // Null exactly when no buffered key is non-null, and NULLs match nothing. `apply_cmp`
        // normalizes `-0.0`/`+0.0` on both operands when it compares this against the streamed
        // key in `matched_mask`, so no normalization is needed here.
        let extreme = ScalarValue::try_from_array(buffered_extreme.extreme(), 0)?;
        self.buffered_extreme = (!extreme.is_null()).then_some(extreme);

        // With no non-null buffered key nothing matches, so `RightSemi` outputs nothing
        // and does not need to read a single streamed batch. `RightAnti`/`RightMark` still
        // have to, since they output all of them (the latter with `mark` false throughout).
        self.state = match (&self.buffered_extreme, self.join_type) {
            (None, JoinType::RightSemi) => {
                let streamed_schema = self.streamed.schema();
                self.streamed = Box::pin(EmptyRecordBatchStream::new(streamed_schema));
                RightExistencePWMJStreamState::Completed
            }
            _ => RightExistencePWMJStreamState::ScanStreamBatches,
        };

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

    /// Fetches one streamed batch, filters or marks it, and pushes the result into
    /// `output_batches`. Once the streamed side is exhausted, flushes the coalescer's
    /// partial batch and hands off to [`Self::drain_output`].
    fn scan_stream_batch(
        &mut self,
        cx: &mut std::task::Context<'_>,
    ) -> Poll<Result<StatefulStreamResult<Option<RecordBatch>>>> {
        if let Some(batch) = self.output_batches.next_completed_batch() {
            return Poll::Ready(Ok(StatefulStreamResult::Ready(Some(batch))));
        }

        match ready!(self.streamed.poll_next_unpin(cx)) {
            None => {
                self.output_batches.finish_buffered_batch()?;
                self.state = RightExistencePWMJStreamState::Draining;
            }
            Some(Ok(batch)) => {
                self.join_metrics.input_batches.add(1);
                self.join_metrics.input_rows.add(batch.num_rows());

                let output = match self.join_type {
                    JoinType::RightMark => self.mark_streamed_batch(&batch)?,
                    _ => self.filter_streamed_batch(&batch)?,
                };
                if output.num_rows() > 0 {
                    self.output_batches.push_batch(output)?;
                }
                // Nothing pushed, or not enough to complete a batch yet: loop back
                // through `poll_next_impl` to poll the next streamed batch.
            }
            Some(Err(err)) => return Poll::Ready(Err(err)),
        }

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

    /// Drains whatever `output_batches` still holds once the streamed side is exhausted.
    fn drain_output(&mut self) -> Result<StatefulStreamResult<Option<RecordBatch>>> {
        match self.output_batches.next_completed_batch() {
            Some(batch) => Ok(StatefulStreamResult::Ready(Some(batch))),
            None => {
                self.state = RightExistencePWMJStreamState::Completed;
                Ok(StatefulStreamResult::Ready(None))
            }
        }
    }

    /// Compares a streamed batch's key against the single buffered extreme, on the same
    /// `buffered OP streamed` orientation the predicate has. `None` when the buffered side has
    /// no non-null key, in which case no streamed row can match anything.
    fn matched_mask(&self, batch: &RecordBatch) -> Result<Option<BooleanArray>> {
        let Some(extreme) = &self.buffered_extreme else {
            return Ok(None);
        };

        let stream_values = ColumnarValue::Array(
            self.on_streamed
                .evaluate(batch)?
                .into_array(batch.num_rows())?,
        );

        // `extreme` is the buffered key, so it goes on the left of the operator, matching the
        // `buffered OP streamed` orientation of the predicate. `apply_cmp` dispatches to the
        // nested-aware comparator for List/Struct keys, unlike the raw arrow
        // `lt`/`lt_eq`/`gt`/`gt_eq` kernels, which reject those types outright.
        let matched = apply_cmp(
            self.operator,
            &ColumnarValue::Scalar(extreme.clone()),
            &stream_values,
        )?
        .into_array(batch.num_rows())?;

        Ok(Some(matched.as_boolean().clone()))
    }

    /// Keeps the streamed rows that have a buffered match (`RightSemi`) or that have none
    /// (`RightAnti`), by comparing each against the single buffered extreme.
    fn filter_streamed_batch(&self, batch: &RecordBatch) -> Result<RecordBatch> {
        let columns = match self.matched_mask(batch)? {
            // No non-null buffered key, so no streamed row matches and `RightAnti` keeps
            // the batch whole. `RightSemi` never gets here: it completed without reading
            // the streamed side.
            None => batch.columns().to_vec(),
            Some(matched) => {
                let predicate = match self.join_type {
                    // A NULL streamed key compares NULL rather than false, and `filter`
                    // already treats NULL as "not selected" -- which is what a
                    // non-matching row is.
                    JoinType::RightSemi => matched,
                    // Anti needs the complement, so those NULLs have to be folded into
                    // false first: `not(NULL)` is NULL, which would drop a row that
                    // matched nothing.
                    _ => not(&boolean_mask_from_filter(&matched))?,
                };

                filter_record_batch(batch, &predicate)?.columns().to_vec()
            }
        };

        // Right existence joins output the streamed columns only. The streamed child's
        // schema is field-for-field equal to the join's own, but rebuild against the
        // latter so the stream's declared schema is what it yields.
        Ok(RecordBatch::try_new(Arc::clone(&self.schema), columns)?)
    }

    /// Keeps every streamed row -- nothing is filtered -- and appends the comparison against
    /// the single buffered extreme as a `mark` column: `true` where some buffered row
    /// matches, `false` everywhere else, including where the streamed key is NULL (the `mark`
    /// column is documented never to be NULL; see `JoinType::LeftMark`).
    fn mark_streamed_batch(&self, batch: &RecordBatch) -> Result<RecordBatch> {
        let mark: ArrayRef = match self.matched_mask(batch)? {
            None => Arc::new(BooleanArray::new(
                BooleanBuffer::new_unset(batch.num_rows()),
                None,
            )),
            Some(matched) => Arc::new(boolean_mask_from_filter(&matched)),
        };

        let mut columns = Vec::with_capacity(batch.num_columns() + 1);
        columns.extend_from_slice(batch.columns());
        columns.push(mark);

        // Right existence joins output the streamed columns (plus `mark` for `RightMark`)
        // only. The streamed child's schema is field-for-field equal to the join's own for
        // those columns, but rebuild against the latter so the stream's declared schema is
        // what it yields.
        Ok(RecordBatch::try_new(Arc::clone(&self.schema), columns)?)
    }
}

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

impl Stream for RightExistencePWMJStream {
    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::sorts::sort::SortExec;
    use crate::{
        ExecutionPlan, ExecutionPlanProperties, common, joins::PiecewiseMergeJoinExec,
        test::TestMemoryExec,
    };
    use arrow::array::{
        DictionaryArray, Float64Array, Int32Array, ListArray, StructArray,
    };
    use arrow::compute::SortOptions;
    use arrow::datatypes::Int32Type;
    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_execution::memory_pool::GreedyMemoryPool;
    use datafusion_execution::runtime_env::RuntimeEnvBuilder;
    use datafusion_physical_expr::expressions::Column;
    use datafusion_physical_expr::{LexOrdering, PhysicalSortExpr};
    use insta::assert_snapshot;

    // Coverage for right existence joins also lives in `pwmj.slt` (both correlation
    // orientations, all four operators, NULLs, key types) and in the differential fuzz test
    // `fuzz_pwmj_matches_nested_loop`, which checks them against
    // `NestedLoopJoinExec` over randomized inputs. The tests here pin the parts SQL cannot
    // observe: which streamed batches were read, and which partition emitted them.

    fn kv_schema() -> Arc<Schema> {
        Arc::new(Schema::new(vec![
            Field::new("id", DataType::Int32, false),
            Field::new("k", DataType::Int32, true),
        ]))
    }

    fn kv_batch(rows: &[(i32, Option<i32>)]) -> RecordBatch {
        let ids: Vec<i32> = rows.iter().map(|(id, _)| *id).collect();
        let keys: Vec<Option<i32>> = rows.iter().map(|(_, k)| *k).collect();
        RecordBatch::try_new(
            kv_schema(),
            vec![
                Arc::new(Int32Array::from(ids)),
                Arc::new(Int32Array::from(keys)),
            ],
        )
        .unwrap()
    }

    fn kv_exec(partitions: &[Vec<RecordBatch>]) -> Arc<dyn ExecutionPlan> {
        TestMemoryExec::try_new_exec(partitions, kv_schema(), None).unwrap()
    }

    /// Right existence joins declare no input ordering requirement, so the buffered sides
    /// below are deliberately **unsorted**: only their min/max matters. That is also why
    /// building the exec directly is faithful here, where the other streams would need a
    /// `SortExec` the tests have to supply by hand.
    fn join(
        buffered: Arc<dyn ExecutionPlan>,
        streamed: Arc<dyn ExecutionPlan>,
        operator: Operator,
        join_type: JoinType,
    ) -> Result<PiecewiseMergeJoinExec> {
        let on = (
            Arc::new(Column::new_with_schema("k", &buffered.schema())?) as _,
            Arc::new(Column::new_with_schema("k", &streamed.schema())?) as _,
        );
        let probe = PiecewiseMergeJoinExec::try_new(
            Arc::clone(&buffered),
            Arc::clone(&streamed),
            on.clone(),
            operator,
            join_type,
            1,
        )?;
        assert!(
            probe.required_input_ordering().iter().all(Option::is_none),
            "right existence joins must not require an input ordering"
        );
        assert!(
            probe
                .input_distribution_requirements()
                .per_child_distributions()
                .all(|d| matches!(
                    d,
                    datafusion_physical_expr::Distribution::UnspecifiedDistribution
                )),
            "right existence joins must not require the buffered side coalesced"
        );
        assert_eq!(
            probe.benefits_from_input_partitioning(),
            vec![false, true],
            "the buffered side must not be fanned out just to fold it"
        );
        PiecewiseMergeJoinExec::try_new(buffered, streamed, on, operator, join_type, 1)
    }

    fn input_batches(join: &PiecewiseMergeJoinExec) -> usize {
        join.metrics()
            .unwrap()
            .sum_by_name("input_batches")
            .expect("input_batches metric")
            .as_usize()
    }

    /// `RightSemi` keeps the streamed rows with at least one buffered match, and outputs
    /// only the streamed columns. `>` needs the buffered maximum, 5, so of the streamed keys
    /// {4, 5, 6} only 4 has some buffered key above it.
    #[tokio::test]
    async fn join_right_semi() -> Result<()> {
        let join = join(
            kv_exec(&[vec![kv_batch(&[(1, Some(5)), (2, Some(1)), (3, Some(2))])]]),
            kv_exec(&[vec![kv_batch(&[
                (10, Some(4)),
                (20, Some(5)),
                (30, Some(6)),
            ])]]),
            Operator::Gt,
            JoinType::RightSemi,
        )?;

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

        assert_snapshot!(batches_to_string(&batches), @r"
        +----+---+
        | id | k |
        +----+---+
        | 10 | 4 |
        +----+---+
        ");
        Ok(())
    }

    /// `RightAnti` is the complement: the streamed rows with no buffered match.
    #[tokio::test]
    async fn join_right_anti() -> Result<()> {
        let join = join(
            kv_exec(&[vec![kv_batch(&[(1, Some(5)), (2, Some(1)), (3, Some(2))])]]),
            kv_exec(&[vec![kv_batch(&[
                (10, Some(4)),
                (20, Some(5)),
                (30, Some(6)),
            ])]]),
            Operator::Gt,
            JoinType::RightAnti,
        )?;

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

        assert_snapshot!(batches_to_string(&batches), @r"
        +----+---+
        | id | k |
        +----+---+
        | 20 | 5 |
        | 30 | 6 |
        +----+---+
        ");
        Ok(())
    }

    /// `RightMark` keeps every streamed row -- unlike `RightSemi`/`RightAnti`, none is
    /// dropped -- and appends a `mark` column: `true` for exactly the rows `RightSemi` would
    /// have kept.
    #[tokio::test]
    async fn join_right_mark() -> Result<()> {
        let join = join(
            kv_exec(&[vec![kv_batch(&[(1, Some(5)), (2, Some(1)), (3, Some(2))])]]),
            kv_exec(&[vec![kv_batch(&[
                (10, Some(4)),
                (20, Some(5)),
                (30, Some(6)),
            ])]]),
            Operator::Gt,
            JoinType::RightMark,
        )?;

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

        assert_snapshot!(batches_to_string(&batches), @r"
        +----+---+-------+
        | id | k | mark  |
        +----+---+-------+
        | 10 | 4 | true  |
        | 20 | 5 | false |
        | 30 | 6 | false |
        +----+---+-------+
        ");
        Ok(())
    }

    fn kv_float_schema() -> Arc<Schema> {
        Arc::new(Schema::new(vec![
            Field::new("id", DataType::Int32, false),
            Field::new("k", DataType::Float64, true),
        ]))
    }

    fn kv_float_batch(rows: &[(i32, Option<f64>)]) -> RecordBatch {
        let ids: Vec<i32> = rows.iter().map(|(id, _)| *id).collect();
        let keys: Vec<Option<f64>> = rows.iter().map(|(_, k)| *k).collect();
        RecordBatch::try_new(
            kv_float_schema(),
            vec![
                Arc::new(Int32Array::from(ids)),
                Arc::new(Float64Array::from(keys)),
            ],
        )
        .unwrap()
    }

    fn kv_float_exec(partitions: &[Vec<RecordBatch>]) -> Arc<dyn ExecutionPlan> {
        TestMemoryExec::try_new_exec(partitions, kv_float_schema(), None).unwrap()
    }

    /// `matched_mask` compares against the buffered extreme with `apply_cmp`, the same total
    /// order (`f64::total_cmp`) `min`/`max` used to fold that extreme in the first place. Under
    /// that order NaN is the largest float, so the buffered max here is NaN and every non-NaN
    /// streamed key marks `true` -- `-Inf`, `0.0`, `-0.0`, and `2.0` are all `< NaN` -- while
    /// NaN itself marks `false` (`NaN < NaN` is false under `total_cmp`, unlike an unordered
    /// IEEE comparison, which would make it incomparable rather than false). `0.0` and `-0.0`
    /// both marking `true` here also confirms they compare equal to each other and to every
    /// ordinary float on this path, not just relative to a `-0.0` buffered key as in the
    /// `LeftMark` case (see the `pwmj.slt` `-0.0` coverage under `LeftMark`). Same data as the
    /// `RIGHT SEMI`/`RIGHT ANTI` NaN coverage in `pwmj.slt`, through `RightMark` instead.
    #[tokio::test]
    async fn join_right_mark_supports_nan_and_negative_zero() -> Result<()> {
        let join = join(
            kv_float_exec(&[vec![kv_float_batch(&[
                (1, Some(1.0)),
                (2, Some(f64::NAN)),
            ])]]),
            kv_float_exec(&[vec![kv_float_batch(&[
                (1, Some(f64::NEG_INFINITY)),
                (2, Some(0.0)),
                (3, Some(-0.0)),
                (4, Some(f64::NAN)),
                (5, Some(2.0)),
            ])]]),
            Operator::Gt,
            JoinType::RightMark,
        )?;

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

        assert_snapshot!(batches_to_string(&batches), @r"
        +----+------+-------+
        | id | k    | mark  |
        +----+------+-------+
        | 1  | -inf | true  |
        | 2  | 0.0  | true  |
        | 3  | -0.0 | true  |
        | 4  | NaN  | false |
        | 5  | 2.0  | true  |
        +----+------+-------+
        ");
        Ok(())
    }

    fn kv_list_schema() -> Arc<Schema> {
        Arc::new(Schema::new(vec![
            Field::new("id", DataType::Int32, false),
            Field::new(
                "k",
                DataType::List(Arc::new(Field::new_list_field(DataType::Int32, true))),
                true,
            ),
        ]))
    }

    fn kv_list_batch(rows: &[(i32, Option<Vec<i32>>)]) -> RecordBatch {
        let ids: Vec<i32> = rows.iter().map(|(id, _)| *id).collect();
        let keys = ListArray::from_iter_primitive::<Int32Type, _, _>(
            rows.iter()
                .map(|(_, k)| k.clone().map(|v| v.into_iter().map(Some))),
        );
        RecordBatch::try_new(
            kv_list_schema(),
            vec![Arc::new(Int32Array::from(ids)), Arc::new(keys)],
        )
        .unwrap()
    }

    fn kv_list_exec(partitions: &[Vec<RecordBatch>]) -> Arc<dyn ExecutionPlan> {
        TestMemoryExec::try_new_exec(partitions, kv_list_schema(), None).unwrap()
    }

    /// List/Struct keys go through `apply_cmp`'s nested comparator, unlike arrow's raw
    /// `lt`/`lt_eq`/`gt`/`gt_eq` kernels, which reject nested types outright -- this pins that
    /// dispatch rather than any particular list-ordering rule. Same shape as `join_right_semi`,
    /// with every key wrapped in a one-element list.
    #[tokio::test]
    async fn join_right_semi_supports_list_keys() -> Result<()> {
        let join = join(
            kv_list_exec(&[vec![kv_list_batch(&[
                (1, Some(vec![5])),
                (2, Some(vec![1])),
                (3, Some(vec![2])),
            ])]]),
            kv_list_exec(&[vec![kv_list_batch(&[
                (10, Some(vec![4])),
                (20, Some(vec![5])),
                (30, Some(vec![6])),
            ])]]),
            Operator::Gt,
            JoinType::RightSemi,
        )?;

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

        assert_snapshot!(batches_to_string(&batches), @r"
        +----+-----+
        | id | k   |
        +----+-----+
        | 10 | [4] |
        +----+-----+
        ");
        Ok(())
    }

    fn kv_struct_schema() -> Arc<Schema> {
        Arc::new(Schema::new(vec![
            Field::new("id", DataType::Int32, false),
            Field::new(
                "k",
                DataType::Struct(vec![Field::new("v", DataType::Int32, true)].into()),
                true,
            ),
        ]))
    }

    fn kv_struct_batch(rows: &[(i32, Option<i32>)]) -> RecordBatch {
        let ids: Vec<i32> = rows.iter().map(|(id, _)| *id).collect();
        let values: Vec<Option<i32>> = rows.iter().map(|(_, k)| *k).collect();
        let is_valid: Vec<bool> = rows.iter().map(|(_, k)| k.is_some()).collect();
        let keys = StructArray::new(
            vec![Field::new("v", DataType::Int32, true)].into(),
            vec![Arc::new(Int32Array::from(values))],
            Some(is_valid.into()),
        );
        RecordBatch::try_new(
            kv_struct_schema(),
            vec![Arc::new(Int32Array::from(ids)), Arc::new(keys)],
        )
        .unwrap()
    }

    fn kv_struct_exec(partitions: &[Vec<RecordBatch>]) -> Arc<dyn ExecutionPlan> {
        TestMemoryExec::try_new_exec(partitions, kv_struct_schema(), None).unwrap()
    }

    /// Struct keys, same shape and expectation as [`join_right_semi_supports_list_keys`].
    #[tokio::test]
    async fn join_right_semi_supports_struct_keys() -> Result<()> {
        let join = join(
            kv_struct_exec(&[vec![kv_struct_batch(&[
                (1, Some(5)),
                (2, Some(1)),
                (3, Some(2)),
            ])]]),
            kv_struct_exec(&[vec![kv_struct_batch(&[
                (10, Some(4)),
                (20, Some(5)),
                (30, Some(6)),
            ])]]),
            Operator::Gt,
            JoinType::RightSemi,
        )?;

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

        assert_snapshot!(batches_to_string(&batches), @r"
        +----+--------+
        | id | k      |
        +----+--------+
        | 10 | {v: 4} |
        +----+--------+
        ");
        Ok(())
    }

    fn kv_dict_schema() -> Arc<Schema> {
        Arc::new(Schema::new(vec![
            Field::new("id", DataType::Int32, false),
            Field::new(
                "k",
                DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
                true,
            ),
        ]))
    }

    fn kv_dict_batch(rows: &[(i32, Option<&str>)]) -> RecordBatch {
        let ids: Vec<i32> = rows.iter().map(|(id, _)| *id).collect();
        let keys: DictionaryArray<Int32Type> = rows.iter().map(|(_, k)| *k).collect();
        RecordBatch::try_new(
            kv_dict_schema(),
            vec![Arc::new(Int32Array::from(ids)), Arc::new(keys)],
        )
        .unwrap()
    }

    fn kv_dict_exec(partitions: &[Vec<RecordBatch>]) -> Arc<dyn ExecutionPlan> {
        TestMemoryExec::try_new_exec(partitions, kv_dict_schema(), None).unwrap()
    }

    /// Dictionary-encoded keys, same shape as [`join_right_semi_supports_list_keys`] with
    /// string values ordered the same as the int cases (`"4" < "5" < "6"`).
    #[tokio::test]
    async fn join_right_semi_supports_dictionary_keys() -> Result<()> {
        let join = join(
            kv_dict_exec(&[vec![kv_dict_batch(&[
                (1, Some("5")),
                (2, Some("1")),
                (3, Some("2")),
            ])]]),
            kv_dict_exec(&[vec![kv_dict_batch(&[
                (10, Some("4")),
                (20, Some("5")),
                (30, Some("6")),
            ])]]),
            Operator::Gt,
            JoinType::RightSemi,
        )?;

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

        assert_snapshot!(batches_to_string(&batches), @r"
        +----+---+
        | id | k |
        +----+---+
        | 10 | 4 |
        +----+---+
        ");
        Ok(())
    }

    /// A NULL key satisfies no comparison predicate, on either side.
    ///
    /// The buffered side is sorted descending with NULLs first, as `<` requires, so the key
    /// this operator needs -- the minimum, 5 -- is the last row and the NULL is nowhere near
    /// it. On the streamed side the NULL-keyed row matches nothing, so `RightSemi` drops it,
    /// `RightAnti` keeps it, and `RightMark` keeps it with `mark` folded to `false`.
    #[tokio::test]
    async fn null_keys_match_nothing() -> Result<()> {
        let buffered =
            || kv_exec(&[vec![kv_batch(&[(1, Some(9)), (2, None), (3, Some(5))])]]);
        let streamed = || {
            kv_exec(&[vec![kv_batch(&[
                (10, Some(5)),
                (20, Some(6)),
                (30, None),
                (40, Some(100)),
            ])]])
        };

        let semi = join(buffered(), streamed(), Operator::Lt, JoinType::RightSemi)?;
        let batches =
            common::collect(semi.execute(0, Arc::new(TaskContext::default()))?).await?;
        assert_snapshot!(batches_to_string(&batches), @r"
        +----+-----+
        | id | k   |
        +----+-----+
        | 20 | 6   |
        | 40 | 100 |
        +----+-----+
        ");

        let anti = join(buffered(), streamed(), Operator::Lt, JoinType::RightAnti)?;
        let batches =
            common::collect(anti.execute(0, Arc::new(TaskContext::default()))?).await?;
        assert_snapshot!(batches_to_string(&batches), @r"
        +----+---+
        | id | k |
        +----+---+
        | 10 | 5 |
        | 30 |   |
        +----+---+
        ");

        // `RightMark`'s NULL-keyed row (id 30) takes a different code path from
        // `all_null_buffered_side_marks_every_row_false`: the buffered extreme here is a real,
        // non-null 5, so `matched_mask` returns `Some` and the NULL streamed key compares NULL
        // rather than short-circuiting on a `None` extreme. `mark_streamed_batch` must still
        // fold that NULL to `false` via `boolean_mask_from_filter`, the same as `RightAnti`
        // folds it to "keep" above -- this is the one test that exercises that fold for `mark`
        // outside of the differential fuzzer's random NULLs.
        let mark = join(buffered(), streamed(), Operator::Lt, JoinType::RightMark)?;
        let batches =
            common::collect(mark.execute(0, Arc::new(TaskContext::default()))?).await?;
        assert_snapshot!(batches_to_string(&batches), @r"
        +----+-----+-------+
        | id | k   | mark  |
        +----+-----+-------+
        | 10 | 5   | false |
        | 20 | 6   | true  |
        | 30 |     | false |
        | 40 | 100 | true  |
        +----+-----+-------+
        ");
        Ok(())
    }

    /// With no non-null buffered key nothing can match, so `RightSemi` is empty however many
    /// streamed rows there are -- and it does not read a single one of them. Asserted through
    /// the `input_batches` metric, which SQL cannot observe.
    #[tokio::test]
    async fn all_null_buffered_side_makes_right_semi_read_nothing() -> Result<()> {
        let join = join(
            kv_exec(&[vec![kv_batch(&[(1, None), (2, None)])]]),
            kv_exec(&[vec![
                kv_batch(&[(10, Some(4))]),
                kv_batch(&[(20, Some(5))]),
                kv_batch(&[(30, Some(6))]),
            ]]),
            Operator::Gt,
            JoinType::RightSemi,
        )?;

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

        assert_eq!(batches.iter().map(|b| b.num_rows()).sum::<usize>(), 0);
        assert_eq!(input_batches(&join), 0, "no streamed batch should be read");
        Ok(())
    }

    /// The same buffered side, here empty rather than all-NULL, sends every streamed row to
    /// `RightAnti` instead. It has to read them all: they are the output.
    #[tokio::test]
    async fn empty_buffered_side_passes_right_anti_through() -> Result<()> {
        let join = join(
            kv_exec(&[vec![kv_batch(&[])]]),
            kv_exec(&[vec![
                kv_batch(&[(10, Some(4))]),
                kv_batch(&[(20, None)]),
                kv_batch(&[(30, Some(6))]),
            ]]),
            Operator::Gt,
            JoinType::RightAnti,
        )?;

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

        assert_snapshot!(batches_to_string(&batches), @r"
        +----+---+
        | id | k |
        +----+---+
        | 10 | 4 |
        | 20 |   |
        | 30 | 6 |
        +----+---+
        ");
        assert_eq!(input_batches(&join), 3);
        Ok(())
    }

    /// The same all-NULL buffered side as the `RightSemi` test above, but for `RightMark`:
    /// nothing can ever match, so every streamed row's `mark` is `false` -- never NULL, even
    /// though the streamed keys include one. `RightMark` still has to read every batch, since
    /// (unlike `RightSemi`) it outputs one row per streamed row regardless of its mark.
    #[tokio::test]
    async fn all_null_buffered_side_marks_every_row_false() -> Result<()> {
        let join = join(
            kv_exec(&[vec![kv_batch(&[(1, None), (2, None)])]]),
            kv_exec(&[vec![
                kv_batch(&[(10, Some(4))]),
                kv_batch(&[(20, None)]),
                kv_batch(&[(30, Some(6))]),
            ]]),
            Operator::Gt,
            JoinType::RightMark,
        )?;

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

        assert_snapshot!(batches_to_string(&batches), @r"
        +----+---+-------+
        | id | k | mark  |
        +----+---+-------+
        | 10 | 4 | false |
        | 20 |   | false |
        | 30 | 6 | false |
        +----+---+-------+
        ");
        assert_eq!(input_batches(&join), 3, "RightMark must read every batch");
        Ok(())
    }

    /// The streamed side's ordering survives this join -- one output batch per streamed batch, in
    /// order, with rows only removed -- so `maintains_input_order` claims it and the operator
    /// advertises the streamed child's ordering as its own. That lets a downstream operator skip
    /// a re-sort, which means a wrong claim here would produce wrong results, not just a slow
    /// plan. The runtime side of it is pinned by the row-order snapshots above.
    #[test]
    fn output_ordering_follows_the_streamed_side() -> Result<()> {
        let streamed_input = kv_exec(&[vec![kv_batch(&[(20, Some(4)), (10, Some(9))])]]);
        let ordering = LexOrdering::new(vec![PhysicalSortExpr::new(
            Arc::new(Column::new_with_schema("id", &streamed_input.schema())?),
            SortOptions::new(true, false),
        )])
        .unwrap();
        let streamed = Arc::new(SortExec::new(ordering.clone(), streamed_input));

        for join_type in [
            JoinType::RightSemi,
            JoinType::RightAnti,
            JoinType::RightMark,
        ] {
            let join = join(
                kv_exec(&[vec![kv_batch(&[(1, Some(5))])]]),
                Arc::clone(&streamed) as _,
                Operator::Gt,
                join_type,
            )?;
            assert_eq!(
                join.properties().output_ordering(),
                Some(&ordering),
                "{join_type} should advertise the streamed side's ordering"
            );
        }

        // The buffered side contributes no column, so its ordering must not leak out: a buffered
        // child sorted on `k` cannot make the join claim anything.
        let buffered_ordering = LexOrdering::new(vec![PhysicalSortExpr::new(
            Arc::new(Column::new("k", 1)),
            SortOptions::new(false, true),
        )])
        .unwrap();
        let sorted_buffered = Arc::new(SortExec::new(
            buffered_ordering,
            kv_exec(&[vec![kv_batch(&[(1, Some(5))])]]),
        ));
        let join = join(
            sorted_buffered as _,
            kv_exec(&[vec![kv_batch(&[(20, Some(4))])]]),
            Operator::Gt,
            JoinType::RightSemi,
        )?;
        assert_eq!(join.properties().output_ordering(), None);
        Ok(())
    }

    /// A zero-row streamed batch still reaches the comparison kernel, which yields an empty
    /// mask rather than erroring, so the batch is filtered away and the surrounding batches
    /// are unaffected. Covered for all three join types since only anti also runs `not` over
    /// it, and mark keeps every row regardless.
    #[tokio::test]
    async fn empty_streamed_batch_is_skipped() -> Result<()> {
        for (join_type, expected) in [
            (JoinType::RightSemi, 1),
            (JoinType::RightAnti, 1),
            (JoinType::RightMark, 2),
        ] {
            let join = join(
                kv_exec(&[vec![kv_batch(&[(1, Some(5)), (2, Some(1))])]]),
                kv_exec(&[vec![
                    kv_batch(&[]),
                    kv_batch(&[(10, Some(4)), (20, Some(9))]),
                    kv_batch(&[]),
                ]]),
                Operator::Gt,
                join_type,
            )?;

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

            // Buffered maximum is 5, so `>` keeps 4 for semi and 9 for anti -- one row each --
            // and `RightMark` keeps both, with no empty batch in between for any of them.
            assert_eq!(
                batches.iter().map(|b| b.num_rows()).sum::<usize>(),
                expected,
                "{join_type}"
            );
            assert!(
                batches.iter().all(|b| b.num_rows() > 0),
                "{join_type} should not yield an empty batch"
            );
            assert_eq!(input_batches(&join), 3, "{join_type}");
        }
        Ok(())
    }

    /// Each streamed batch here is one matching row, so without coalescing the stream would
    /// hand back 5 one-row batches. `batch_size` 2 packs them into 3 instead, pinning that
    /// `output_batches` actually merges across streamed-batch boundaries rather than just
    /// forwarding `filter_streamed_batch`'s output directly.
    #[tokio::test]
    async fn output_is_coalesced_to_batch_size() -> Result<()> {
        let join = join(
            kv_exec(&[vec![kv_batch(&[(1, Some(10))])]]),
            kv_exec(&[vec![
                kv_batch(&[(10, Some(1))]),
                kv_batch(&[(20, Some(2))]),
                kv_batch(&[(30, Some(3))]),
                kv_batch(&[(40, Some(4))]),
                kv_batch(&[(50, Some(5))]),
            ]]),
            Operator::Gt,
            JoinType::RightSemi,
        )?;

        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.iter().map(|b| b.num_rows()).collect::<Vec<_>>(),
            vec![2, 2, 1],
            "5 matching rows over 5 input batches should pack into ceil(5/2) = 3 output \
             batches of at most `batch_size` rows each"
        );
        assert_eq!(
            input_batches(&join),
            5,
            "every streamed batch is still read"
        );
        Ok(())
    }

    /// `output_is_coalesced_to_batch_size` above pins that coalescing happens; this pins that
    /// it doesn't reorder rows while doing it. The streamed side is genuinely sorted (via
    /// `SortExec`, the same claim `output_ordering_follows_the_streamed_side` checks at the
    /// planning level), filtering drops rows unevenly across it, and a small `batch_size`
    /// forces `output_batches` to repack across what were originally separate sorted
    /// `SortExec` output batches. `BatchCoalescer`'s `completed` buffer is a plain FIFO
    /// `VecDeque` in arrow-rs (`push_back`/`pop_front`, no sort), so this should hold
    /// regardless -- the point is to check it at runtime, not just reason about it.
    #[tokio::test]
    async fn coalescing_does_not_reorder_a_sorted_streamed_side() -> Result<()> {
        let streamed_input = kv_exec(&[vec![kv_batch(&[
            (50, Some(5)),
            (10, Some(199)),
            (90, Some(6)),
            (30, Some(200)),
            (20, Some(7)),
            (70, Some(8)),
            (40, Some(199)),
            (60, Some(9)),
        ])]]);
        let ordering = LexOrdering::new(vec![PhysicalSortExpr::new(
            Arc::new(Column::new_with_schema("id", &streamed_input.schema())?),
            SortOptions::new(false, false),
        )])
        .unwrap();
        let streamed = Arc::new(SortExec::new(ordering, streamed_input));

        // Buffered max is 100, so `>` keeps only streamed rows with k < 100 -- ids 10, 30, 40
        // (k in the 100s) are filtered out, unevenly across the sorted id order, so the
        // survivors (20, 50, 60, 70, 90) don't line up with any one original batch boundary.
        let join = join(
            kv_exec(&[vec![kv_batch(&[(1, Some(100))])]]),
            streamed as _,
            Operator::Gt,
            JoinType::RightSemi,
        )?;

        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?;

        let ids: Vec<i32> = batches
            .iter()
            .flat_map(|b| b.column(0).as_primitive::<Int32Type>().values().to_vec())
            .collect();
        assert_eq!(
            ids,
            vec![20, 50, 60, 70, 90],
            "coalescing must not disturb the streamed side's sorted order"
        );
        assert_eq!(
            batches.iter().map(|b| b.num_rows()).collect::<Vec<_>>(),
            vec![2, 2, 1],
            "5 surviving rows packed to batch_size = 2 confirms the coalescer, not a \
             pass-through, produced this shape"
        );
        Ok(())
    }

    /// The `RightMark` sibling of the test above: `mark_streamed_batch` never filters, so
    /// every row (not a subset) has to stay in the streamed side's sorted order once the
    /// coalescer repacks across the original `SortExec` batch boundaries, and each row's
    /// `mark` has to travel with the right `id` through that repacking.
    #[tokio::test]
    async fn coalescing_does_not_reorder_a_sorted_streamed_side_for_mark() -> Result<()> {
        let streamed_input = kv_exec(&[vec![kv_batch(&[
            (50, Some(5)),
            (10, Some(199)),
            (90, Some(6)),
            (30, Some(200)),
            (20, Some(7)),
            (70, Some(8)),
            (40, Some(199)),
            (60, Some(9)),
        ])]]);
        let ordering = LexOrdering::new(vec![PhysicalSortExpr::new(
            Arc::new(Column::new_with_schema("id", &streamed_input.schema())?),
            SortOptions::new(false, false),
        )])
        .unwrap();
        let streamed = Arc::new(SortExec::new(ordering, streamed_input));

        // Buffered max is 100, so `mark` is true for k < 100 -- ids 10, 30, 40 (k in the
        // 100s) are false, unevenly across the sorted id order, so the coalescer must not
        // only preserve order but keep each id's mark paired with it while repacking.
        let join = join(
            kv_exec(&[vec![kv_batch(&[(1, Some(100))])]]),
            streamed as _,
            Operator::Gt,
            JoinType::RightMark,
        )?;

        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?;

        let ids: Vec<i32> = batches
            .iter()
            .flat_map(|b| b.column(0).as_primitive::<Int32Type>().values().to_vec())
            .collect();
        let marks: Vec<bool> = batches
            .iter()
            .flat_map(|b| b.column(2).as_boolean().values().iter())
            .collect();
        assert_eq!(
            ids,
            vec![10, 20, 30, 40, 50, 60, 70, 90],
            "coalescing must not disturb the streamed side's sorted order, even though \
             RightMark keeps every row rather than a subset"
        );
        assert_eq!(
            marks,
            vec![false, true, false, false, true, true, true, true],
            "each id's mark must travel with it through the coalescer's repacking"
        );
        assert_eq!(
            batches.iter().map(|b| b.num_rows()).collect::<Vec<_>>(),
            vec![2, 2, 2, 2],
            "8 rows packed to batch_size = 2 confirms the coalescer, not a pass-through, \
             produced this shape"
        );
        Ok(())
    }

    /// The buffered side is folded to one key as it streams in and never materialized, so this
    /// join runs in a memory pool far smaller than that side. 20k buffered rows is >80 KB of
    /// Int32 keys alone and ~160 KB of batches; the pool here is 64 KB, which the collecting
    /// path cannot fit -- it reserves every batch, then the concatenation, then the key array.
    /// The fold needs only the one batch's key array it is reducing (~8 KB), which it does
    /// reserve, so the pool is sized above that and well below the collecting path.
    ///
    /// This is the assertion that pins the retained buffered state at one row. `build_mem_used`
    /// is checked too, since a regression to collecting would show up there even under a
    /// generous pool.
    #[tokio::test]
    async fn buffered_side_is_folded_not_collected() -> Result<()> {
        let buffered: Vec<RecordBatch> = (0..10)
            .map(|b| {
                kv_batch(
                    &(0..2000)
                        .map(|i| (i, Some(b * 2000 + i)))
                        .collect::<Vec<_>>(),
                )
            })
            .collect();

        let join = join(
            kv_exec(&[buffered]),
            kv_exec(&[vec![kv_batch(&[(1, Some(0)), (2, Some(19_999))])]]),
            Operator::Gt,
            JoinType::RightSemi,
        )?;

        let task_ctx = Arc::new(
            TaskContext::default().with_runtime(Arc::new(
                RuntimeEnvBuilder::new()
                    .with_memory_pool(Arc::new(GreedyMemoryPool::new(64 * 1024)))
                    .build()?,
            )),
        );
        let stream = join.execute(0, task_ctx)?;
        let batches = common::collect(stream).await?;

        // Buffered maximum is 19999, so `>` keeps only the streamed 0.
        assert_snapshot!(batches_to_string(&batches), @r"
        +----+---+
        | id | k |
        +----+---+
        | 1  | 0 |
        +----+---+
        ");

        // What is held is one row, not 20k.
        let build_mem_used = join
            .metrics()
            .unwrap()
            .sum_by_name("build_mem_used")
            .expect("build_mem_used metric")
            .as_usize();
        assert!(
            build_mem_used < 1024,
            "buffered state should be a single key, got {build_mem_used} bytes"
        );
        Ok(())
    }

    /// The key array a partition is reducing is transient but as wide as the batch, and it is
    /// reserved for as long as it is held. A pool that cannot fit one of them fails the join
    /// rather than allocating outside the accounting -- which is what keeps the memory claim
    /// honest, since without the reservation this fold would simply succeed.
    #[tokio::test]
    async fn folding_reserves_the_batch_key_array() -> Result<()> {
        let join = join(
            kv_exec(&[vec![kv_batch(
                &(0..2000).map(|i| (i, Some(i))).collect::<Vec<_>>(),
            )]]),
            kv_exec(&[vec![kv_batch(&[(1, Some(0))])]]),
            Operator::Gt,
            JoinType::RightSemi,
        )?;

        let task_ctx = Arc::new(
            TaskContext::default().with_runtime(Arc::new(
                RuntimeEnvBuilder::new()
                    .with_memory_pool(Arc::new(GreedyMemoryPool::new(1024)))
                    .build()?,
            )),
        );
        let err = common::collect(join.execute(0, task_ctx)?)
            .await
            .expect_err("a 2000-row key array should not fit a 1 KB pool");
        assert!(
            err.to_string().contains("PiecewiseMergeJoinBufferedFold"),
            "expected the fold's reservation to fail, got: {err}"
        );
        Ok(())
    }

    /// A min/max combines across partitions, so the buffered side is not required to be
    /// coalesced -- and every partition of it has to be consumed. The deciding key here is in
    /// the **last** buffered partition, so reading only partition 0 (which the other streams do,
    /// since they require `SinglePartition`) silently loses it and changes the answer.
    #[tokio::test]
    async fn every_buffered_partition_is_folded() -> Result<()> {
        // Buffered maxima per partition: 1, 3, 50. Only the last admits the streamed 40.
        let buffered = vec![
            vec![kv_batch(&[(1, Some(0)), (2, Some(1))])],
            vec![kv_batch(&[(3, Some(3))])],
            vec![kv_batch(&[(4, Some(2)), (5, Some(50))])],
        ];
        let streamed = || kv_exec(&[vec![kv_batch(&[(10, Some(2)), (20, Some(40))])]]);

        let semi = join(
            kv_exec(&buffered),
            streamed(),
            Operator::Gt,
            JoinType::RightSemi,
        )?;
        assert_eq!(semi.buffered().output_partitioning().partition_count(), 3);
        let batches =
            common::collect(semi.execute(0, Arc::new(TaskContext::default()))?).await?;
        assert_snapshot!(batches_to_string(&batches), @r"
        +----+----+
        | id | k  |
        +----+----+
        | 10 | 2  |
        | 20 | 40 |
        +----+----+
        ");

        let anti = join(
            kv_exec(&buffered),
            streamed(),
            Operator::Gt,
            JoinType::RightAnti,
        )?;
        let batches =
            common::collect(anti.execute(0, Arc::new(TaskContext::default()))?).await?;
        assert_eq!(batches.iter().map(|b| b.num_rows()).sum::<usize>(), 0);

        // All three partitions were read, not just the first.
        assert_eq!(input_batches(&semi), 1, "streamed batches");
        let build_batches = semi
            .metrics()
            .unwrap()
            .sum_by_name("build_input_batches")
            .expect("build_input_batches metric")
            .as_usize();
        assert_eq!(
            build_batches, 3,
            "every buffered partition should be folded"
        );
        Ok(())
    }

    /// Unlike `LeftSemi`/`LeftAnti`, where one elected partition emits everything at the end,
    /// each streamed partition here emits its own rows as it reads them -- so the join's N
    /// advertised output partitions are all live.
    #[tokio::test]
    async fn every_streamed_partition_emits() -> Result<()> {
        let join = join(
            kv_exec(&[vec![kv_batch(&[(1, Some(5)), (2, Some(1))])]]),
            kv_exec(&[
                vec![kv_batch(&[(10, Some(4)), (20, Some(9))])],
                vec![kv_batch(&[(30, Some(0)), (40, Some(7))])],
            ]),
            Operator::Gt,
            JoinType::RightSemi,
        )?;

        assert_eq!(join.properties().output_partitioning().partition_count(), 2);

        let task_ctx = Arc::new(TaskContext::default());
        let mut per_partition = Vec::new();
        for partition in 0..2 {
            let stream = join.execute(partition, Arc::clone(&task_ctx))?;
            per_partition.push(common::collect(stream).await?);
        }

        // Buffered maximum is 5: partition 0 keeps 4, partition 1 keeps 0.
        for (partition, batches) in per_partition.iter().enumerate() {
            assert_eq!(
                batches.iter().map(|b| b.num_rows()).sum::<usize>(),
                1,
                "partition {partition} should have emitted its own row"
            );
        }
        let out = arrow::compute::concat_batches(
            &join.schema(),
            per_partition.iter().flatten(),
        )?;
        assert_snapshot!(batches_to_string(&[out]), @r"
        +----+---+
        | id | k |
        +----+---+
        | 10 | 4 |
        | 30 | 0 |
        +----+---+
        ");
        Ok(())
    }
}