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

//! Stream implementation for Hash Join
//!
//! This module implements [`HashJoinStream`], the streaming engine for
//! [`super::HashJoinExec`]. See comments in [`HashJoinStream`] for more details.

use std::sync::Arc;
use std::task::Poll;

use crate::coalesce::{LimitedBatchCoalescer, PushBatchStatus};
use crate::joins::Map;
use crate::joins::PartitionMode;
use crate::joins::hash_join::exec::JoinLeftData;
use crate::joins::hash_join::not_in::NotInProbe;
use crate::joins::hash_join::shared_bounds::{
    PartitionBounds, PartitionBuildData, SharedBuildAccumulator,
};
use crate::joins::join_hash_map::ProbeOffset;
use crate::joins::join_hash_map::ProbeOffset::AtRow;
use crate::joins::probe_completion::{Completion, ProbeSideSummary};
use crate::joins::utils::{
    JoinKeyComparator, OnceFut, equal_rows_arr_with_normalized_left, matchable_join_keys,
};
use crate::stream::EmptyRecordBatchStream;
use crate::{
    RecordBatchStream, SendableRecordBatchStream, handle_state,
    hash_utils::create_hashes,
    joins::utils::{
        BuildProbeJoinMetrics, ColumnIndex, JoinFilter, JoinHashMapType,
        StatefulStreamResult, adjust_indices_by_join_type, apply_join_filter_to_indices,
        build_batch_empty_build_side, build_batch_from_indices,
        need_produce_result_in_final,
    },
};

use arrow::array::{Array, ArrayRef, UInt32Array, UInt64Array};
use arrow::buffer::{BooleanBuffer, NullBuffer};
use arrow::datatypes::{Schema, SchemaRef};
use arrow::record_batch::RecordBatch;
use datafusion_common::{
    JoinSide, JoinType, NullEquality, Result, internal_datafusion_err, internal_err,
};
use datafusion_physical_expr::PhysicalExprRef;

use datafusion_common::hash_utils::RandomState;
use datafusion_physical_expr_common::utils::evaluate_expressions_to_arrays;
use futures::{Stream, StreamExt, ready};

/// Represents build-side of hash join.
pub(super) enum BuildSide {
    /// Indicates that build-side not collected yet
    Initial(BuildSideInitialState),
    /// Indicates that build-side data has been collected
    Ready(BuildSideReadyState),
}

/// Container for BuildSide::Initial related data
pub(super) struct BuildSideInitialState {
    /// Future for building hash table from build-side input
    pub(super) left_fut: OnceFut<JoinLeftData>,
}

/// Container for BuildSide::Ready related data
pub(super) struct BuildSideReadyState {
    /// Collected build-side data
    left_data: Arc<JoinLeftData>,
}

impl BuildSide {
    /// Tries to extract BuildSideInitialState from BuildSide enum.
    /// Returns an error if state is not Initial.
    fn try_as_initial_mut(&mut self) -> Result<&mut BuildSideInitialState> {
        match self {
            BuildSide::Initial(state) => Ok(state),
            _ => internal_err!("Expected build side in initial state"),
        }
    }

    /// Tries to extract BuildSideReadyState from BuildSide enum.
    /// Returns an error if state is not Ready.
    fn try_as_ready(&self) -> Result<&BuildSideReadyState> {
        match self {
            BuildSide::Ready(state) => Ok(state),
            _ => internal_err!("Expected build side in ready state"),
        }
    }

    /// Tries to extract BuildSideReadyState from BuildSide enum.
    /// Returns an error if state is not Ready.
    fn try_as_ready_mut(&mut self) -> Result<&mut BuildSideReadyState> {
        match self {
            BuildSide::Ready(state) => Ok(state),
            _ => internal_err!("Expected build side in ready state"),
        }
    }
}

/// Represents state of HashJoinStream
///
/// Expected state transitions performed by HashJoinStream are:
///
/// ```text
///
///       WaitBuildSide
///             │
///             â–¼
///  ┌─► FetchProbeBatch ───► ExhaustedProbeSide ──────────► Completed
///  │          │                     │                          ▲
///  │          ▼                     ▼                          │
///  └─ ProcessProbeBatch      ┌─► EmitUnmatchedBuildRows ───────┘
///                            └──────────┘
/// ```
///
/// `ExhaustedProbeSide` moves to `EmitUnmatchedBuildRows` only for join types
/// that emit build-side rows after the probe side is exhausted (see
/// [`need_produce_result_in_final`]), and only in the partition that finished
/// probing last. That state re-enters itself once per emitted chunk of at most
/// `batch_size` rows.
#[derive(Debug)]
pub(super) enum HashJoinStreamState {
    /// Initial state for HashJoinStream indicating that build-side data not collected yet
    WaitBuildSide,
    /// Waiting for bounds to be reported by all partitions
    WaitPartitionBoundsReport,
    /// Indicates that build-side has been collected, and stream is ready for fetching probe-side
    FetchProbeBatch,
    /// Indicates that non-empty batch has been fetched from probe-side, and is ready to be processed
    ProcessProbeBatch(ProcessProbeBatchState),
    /// Indicates that probe-side has been fully processed
    ExhaustedProbeSide,
    /// Indicates that the probe side has been fully processed by every
    /// partition, and this stream is emitting the final build-side rows
    /// (unmatched rows, or matched rows for `LeftSemi`) in chunks
    EmitUnmatchedBuildRows(EmitUnmatchedBuildRowsState),
    /// Indicates that HashJoinStream execution is completed
    Completed,
}

impl HashJoinStreamState {
    /// Tries to extract ProcessProbeBatchState from HashJoinStreamState enum.
    /// Returns an error if state is not ProcessProbeBatchState.
    fn try_as_process_probe_batch_mut(&mut self) -> Result<&mut ProcessProbeBatchState> {
        match self {
            HashJoinStreamState::ProcessProbeBatch(state) => Ok(state),
            _ => internal_err!("Expected hash join stream in ProcessProbeBatch state"),
        }
    }

    /// Tries to extract EmitUnmatchedBuildRowsState from HashJoinStreamState enum.
    /// Returns an error if state is not EmitUnmatchedBuildRows.
    fn try_as_emit_unmatched_build_rows_mut(
        &mut self,
    ) -> Result<&mut EmitUnmatchedBuildRowsState> {
        match self {
            HashJoinStreamState::EmitUnmatchedBuildRows(state) => Ok(state),
            _ => {
                internal_err!("Expected hash join stream in EmitUnmatchedBuildRows state")
            }
        }
    }
}

/// Container for HashJoinStreamState::ProcessProbeBatch related data
#[derive(Debug)]
pub(super) struct ProcessProbeBatchState {
    /// Current probe-side batch
    batch: RecordBatch,
    /// Probe-side on expressions values
    values: Vec<ArrayRef>,
    /// Combined validity of the probe-side key columns, set when NULL keys
    /// exist and cannot match (`NullEquality::NullEqualsNothing`); NULL rows
    /// are skipped during JoinHashMap lookups
    valid_keys: Option<NullBuffer>,
    /// Starting offset for JoinHashMap lookups
    offset: ProbeOffset,
    /// Max joined probe-side index from current batch
    joined_probe_idx: Option<usize>,
    /// Max probe-side index with a join-key match from current batch, before
    /// the join filter is applied (unlike `joined_probe_idx`). Lets
    /// `probe_hit_rate` and `avg_fanout` count a probe row whose matches span
    /// several chunks only once.
    matched_probe_idx: Option<u32>,
    /// Key comparator for this batch, built on first use and reused by every
    /// chunk
    key_comparator: Option<JoinKeyComparator>,
}

impl ProcessProbeBatchState {
    fn advance(&mut self, offset: ProbeOffset, joined_probe_idx: Option<usize>) {
        self.offset = offset;
        if joined_probe_idx.is_some() {
            self.joined_probe_idx = joined_probe_idx;
        }
    }

    /// Returns how many probe rows in `right_indices`, the join-key matches of
    /// the current chunk, have not been counted by a previous chunk of this
    /// probe batch, and records the last matched index in `matched_probe_idx`.
    fn count_new_matched_probe_rows(&mut self, right_indices: &UInt32Array) -> usize {
        let values = right_indices.values();
        let mut count = count_distinct_sorted_indices(right_indices);
        // A probe row whose matches span a chunk boundary is the last index of the
        // previous chunk and the first index of this one; count it only once.
        if let (Some(&first), Some(&last)) = (values.first(), values.last()) {
            if Some(first) == self.matched_probe_idx {
                count -= 1;
            }
            self.matched_probe_idx = Some(last);
        }
        count
    }

    /// Returns whether the next lookup is the first chunk of this probe batch.
    ///
    /// A probe batch starts at `AtRow { row: 0 }`, and a lookup never returns
    /// that offset (see [`ProbeOffset`]), so this holds only before the first
    /// lookup.
    fn is_first_chunk(&self) -> bool {
        self.offset == AtRow { row: 0 }
    }
}

/// Container for HashJoinStreamState::EmitUnmatchedBuildRows related data
#[derive(Debug, Clone)]
pub(super) struct EmitUnmatchedBuildRowsState {
    /// Snapshot of the build-side visited bitmap, one bit per build row.
    ///
    /// Taken once every probe partition has reported completion, so no
    /// further updates to the shared bitmap are possible and the snapshot
    /// can be scanned without holding its lock.
    visited: BooleanBuffer,
    /// Index of the next build row to examine
    cursor: usize,
    /// What every probe partition together saw, needed by the null-aware
    /// post-processing of each chunk. Captured with the bitmap snapshot
    /// because [`JoinLeftData::report_probe_completed`] hands it out once.
    probe_summary: ProbeSideSummary,
}

/// Lifecycle of this partition's build-data report to the shared coordinator.
///
/// `Scheduled` means the reporting `OnceFut` has been constructed but is lazy:
/// the coordinator has not necessarily observed the report. Only `Delivered`
/// guarantees the coordinator saw it, so `Drop` must still cancel a `Scheduled`
/// partition — otherwise sibling partitions can wait forever for a report that
/// never runs.
#[derive(Debug, PartialEq, Eq)]
enum BuildReportState {
    NotReported,
    Scheduled,
    Delivered,
    Canceled,
    Finalized,
}

/// Owns the stream-side lifecycle for one partition's build-data report.
struct BuildReportHandle {
    partition: usize,
    mode: PartitionMode,
    build_accumulator: Option<Arc<SharedBuildAccumulator>>,
    waiter: Option<OnceFut<()>>,
    state: BuildReportState,
}

impl BuildReportHandle {
    fn new(
        partition: usize,
        mode: PartitionMode,
        build_accumulator: Option<Arc<SharedBuildAccumulator>>,
    ) -> Self {
        Self {
            partition,
            mode,
            build_accumulator,
            waiter: None,
            state: BuildReportState::NotReported,
        }
    }

    fn has_accumulator(&self) -> bool {
        self.build_accumulator.is_some()
    }

    fn schedule(&mut self, build_data: PartitionBuildData) {
        let Some(build_accumulator) = &self.build_accumulator else {
            // Defensive no-op terminal state; current callers avoid scheduling
            // unless an accumulator is present.
            self.finalize();
            return;
        };

        debug_assert!(matches!(self.state, BuildReportState::NotReported));
        let acc = Arc::clone(build_accumulator);
        self.waiter = Some(OnceFut::new(async move {
            acc.report_build_data(build_data).await
        }));
        self.state = BuildReportState::Scheduled;
    }

    fn poll_delivery(&mut self, cx: &mut std::task::Context<'_>) -> Poll<Result<()>> {
        if let Some(ref mut fut) = self.waiter {
            ready!(fut.get_shared(cx))?;
            if !matches!(self.state, BuildReportState::Delivered) {
                debug_assert!(matches!(self.state, BuildReportState::Scheduled));
                self.state = BuildReportState::Delivered;
            }
        }
        Poll::Ready(Ok(()))
    }

    fn cancel_pending(&mut self) {
        if matches!(
            self.state,
            BuildReportState::Delivered
                | BuildReportState::Canceled
                | BuildReportState::Finalized
        ) {
            return;
        }

        if self.mode == PartitionMode::Partitioned
            && let Some(build_accumulator) = &self.build_accumulator
        {
            build_accumulator.report_canceled_partition(self.partition);
            self.state = BuildReportState::Canceled;
        } else {
            self.finalize();
        }
    }

    fn finalize(&mut self) {
        self.state = BuildReportState::Finalized;
    }

    #[cfg(test)]
    fn state(&self) -> &BuildReportState {
        &self.state
    }
}

impl Drop for BuildReportHandle {
    fn drop(&mut self) {
        self.cancel_pending();
    }
}

/// [`Stream`] for [`super::HashJoinExec`] that does the actual join.
///
/// This stream:
///
/// - Collecting the build side (left input) into a hash map
/// - Iterating over the probe side (right input) in streaming fashion
/// - Looking up matches against the hash table and applying join filters
/// - Producing joined [`RecordBatch`]es incrementally
/// - Emitting unmatched rows for outer/semi/anti joins in the final stage
pub(super) struct HashJoinStream {
    /// Partition identifier for debugging and determinism
    partition: usize,
    /// Input schema
    schema: Arc<Schema>,
    /// equijoin columns from the right (probe side)
    on_right: Vec<PhysicalExprRef>,
    /// optional join filter
    filter: Option<JoinFilter>,
    /// type of the join (left, right, semi, etc)
    join_type: JoinType,
    /// right (probe) input
    right: SendableRecordBatchStream,
    /// Random state used for hashing initialization
    random_state: RandomState,
    /// Metrics
    join_metrics: BuildProbeJoinMetrics,
    /// Information of index and left / right placement of columns
    column_indices: Vec<ColumnIndex>,
    /// Defines the null equality for the join.
    null_equality: NullEquality,
    /// State of the stream
    state: HashJoinStreamState,
    /// Build side
    build_side: BuildSide,
    /// Maximum output batch size
    batch_size: usize,
    /// Scratch space for computing hashes
    hashes_buffer: Vec<u64>,
    /// Scratch space for probe indices during hash lookup
    probe_indices_buffer: Vec<u32>,
    /// Scratch space for build indices during hash lookup
    build_indices_buffer: Vec<u64>,

    /// This stream's `NOT IN` work, for a null-aware join (the build side
    /// says whether it is one, see [`JoinLeftData::not_in`]).
    not_in: NotInProbe,

    /// Specifies whether the right side has an ordering to potentially preserve
    right_side_ordered: bool,
    /// Owns this partition's build-data report lifecycle.
    build_report: BuildReportHandle,
    /// Partitioning mode to use
    mode: PartitionMode,
    /// Output buffer for coalescing small batches into larger ones with optional fetch limit.
    /// Uses `LimitedBatchCoalescer` to efficiently combine batches and absorb limit with 'fetch'
    output_buffer: LimitedBatchCoalescer,
}

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

/// Executes lookups by hash against JoinHashMap and resolves potential
/// hash collisions.
/// Returns build/probe indices satisfying the equality condition, along with
/// (optional) starting point for next iteration.
///
/// `build_side_values` must come from [`JoinLeftData::values()`] (or be
/// derived from it), where float `-0.0` is already rewritten to `+0.0`. The
/// key comparison does not normalize the build side again, so raw build keys
/// holding `-0.0` would fail to match `+0.0` on the probe side.
///
/// # Example
///
/// For `LEFT.b1 = RIGHT.b2`:
/// LEFT (build) Table:
/// ```text
///  a1  b1  c1
///  1   1   10
///  3   3   30
///  5   5   50
///  7   7   70
///  9   8   90
///  11  8   110
///  13   10  130
/// ```
///
/// RIGHT (probe) Table:
/// ```text
///  a2   b2  c2
///  2    2   20
///  4    4   40
///  6    6   60
///  8    8   80
/// 10   10  100
/// 12   10  120
/// ```
///
/// The result is
/// ```text
/// "+----+----+-----+----+----+-----+",
/// "| a1 | b1 | c1  | a2 | b2 | c2  |",
/// "+----+----+-----+----+----+-----+",
/// "| 9  | 8  | 90  | 8  | 8  | 80  |",
/// "| 11 | 8  | 110 | 8  | 8  | 80  |",
/// "| 13 | 10 | 130 | 10 | 10 | 100 |",
/// "| 13 | 10 | 130 | 12 | 10 | 120 |",
/// "+----+----+-----+----+----+-----+"
/// ```
///
/// And the result of build and probe indices are:
/// ```text
/// Build indices: 4, 5, 6, 6
/// Probe indices: 3, 3, 4, 5
/// ```
#[expect(clippy::too_many_arguments)]
pub(super) fn lookup_join_hashmap(
    build_hashmap: &dyn JoinHashMapType,
    build_side_values: &[ArrayRef],
    probe_side_values: &[ArrayRef],
    null_equality: NullEquality,
    hashes_buffer: &[u64],
    valid_keys: Option<&NullBuffer>,
    limit: usize,
    offset: ProbeOffset,
    probe_indices_buffer: &mut Vec<u32>,
    build_indices_buffer: &mut Vec<u64>,
    key_comparator: &mut Option<JoinKeyComparator>,
) -> Result<(UInt64Array, UInt32Array, Option<ProbeOffset>)> {
    let next_offset = build_hashmap.get_matched_indices_with_limit_offset(
        hashes_buffer,
        valid_keys,
        limit,
        offset,
        probe_indices_buffer,
        build_indices_buffer,
    );

    let build_indices_unfiltered: UInt64Array =
        std::mem::take(build_indices_buffer).into();
    let probe_indices_unfiltered: UInt32Array =
        std::mem::take(probe_indices_buffer).into();

    let (build_indices, probe_indices) = equal_rows_arr_with_normalized_left(
        &build_indices_unfiltered,
        &probe_indices_unfiltered,
        build_side_values,
        probe_side_values,
        null_equality,
        key_comparator,
    )?;

    // Reclaim buffers
    *build_indices_buffer = build_indices_unfiltered.into_parts().1.into();
    *probe_indices_buffer = probe_indices_unfiltered.into_parts().1.into();

    Ok((build_indices, probe_indices, next_offset))
}

/// Counts the number of distinct elements in the input array.
///
/// The input array must be sorted (e.g., `[0, 1, 1, 2, 2, ...]`) and contain no null values.
#[inline]
fn count_distinct_sorted_indices(indices: &UInt32Array) -> usize {
    if indices.is_empty() {
        return 0;
    }

    debug_assert_eq!(indices.null_count(), 0);

    let values_buf = indices.values();
    let values = values_buf.as_ref();
    let mut iter = values.iter();
    let Some(&first) = iter.next() else {
        return 0;
    };

    let mut count = 1usize;
    let mut last = first;
    for &value in iter {
        if value != last {
            last = value;
            count += 1;
        }
    }
    count
}

impl HashJoinStream {
    #[expect(clippy::too_many_arguments)]
    pub(super) fn new(
        partition: usize,
        schema: Arc<Schema>,
        on_right: Vec<PhysicalExprRef>,
        filter: Option<JoinFilter>,
        join_type: JoinType,
        right: SendableRecordBatchStream,
        random_state: RandomState,
        join_metrics: BuildProbeJoinMetrics,
        column_indices: Vec<ColumnIndex>,
        null_equality: NullEquality,
        state: HashJoinStreamState,
        build_side: BuildSide,
        batch_size: usize,
        hashes_buffer: Vec<u64>,
        right_side_ordered: bool,
        build_accumulator: Option<Arc<SharedBuildAccumulator>>,
        mode: PartitionMode,
        fetch: Option<usize>,
    ) -> Self {
        // Create output buffer with coalescing and optional fetch limit.
        let output_buffer =
            LimitedBatchCoalescer::new(Arc::clone(&schema), batch_size, fetch);

        Self {
            partition,
            schema,
            on_right,
            filter,
            join_type,
            right,
            random_state,
            join_metrics,
            column_indices,
            null_equality,
            state,
            build_side,
            batch_size,
            hashes_buffer,
            probe_indices_buffer: Vec::with_capacity(batch_size),
            build_indices_buffer: Vec::with_capacity(batch_size),
            not_in: NotInProbe::default(),
            right_side_ordered,
            build_report: BuildReportHandle::new(partition, mode, build_accumulator),
            mode,
            output_buffer,
        }
    }

    /// Returns the next state after the build side has been fully collected
    /// and any required build-side coordination has completed.
    fn state_after_build_ready(
        join_type: JoinType,
        left_data: &JoinLeftData,
    ) -> HashJoinStreamState {
        let build_empty = !left_data.has_build_rows();
        // The map can be empty even when the build side has rows: under
        // `NullEqualsNothing`, build rows with a NULL join key are omitted. For
        // join types whose every output row requires a build match, that still
        // guarantees an empty result, so we can skip scanning the probe side.
        let map_empty = !left_data.has_matchable_build_rows();

        if (build_empty && join_type.empty_build_side_produces_empty_result())
            || (map_empty && join_type.empty_map_produces_empty_result())
        {
            HashJoinStreamState::Completed
        } else {
            HashJoinStreamState::FetchProbeBatch
        }
    }

    /// Transitions state after build-side data has been collected, automatically
    /// reporting build data to the accumulator when one is present.
    ///
    /// If a `build_accumulator` is configured, this method constructs the
    /// appropriate [`PartitionBuildData`], schedules the reporting future, and
    /// returns [`HashJoinStreamState::WaitPartitionBoundsReport`]. Otherwise it
    /// delegates to [`Self::state_after_build_ready`].
    fn transition_after_build_collected(
        &mut self,
        left_data: &Arc<JoinLeftData>,
    ) -> HashJoinStreamState {
        if !self.build_report.has_accumulator() {
            return Self::state_after_build_ready(self.join_type, left_data.as_ref());
        }

        let pushdown = left_data.membership().clone();
        let bounds = left_data
            .bounds()
            .cloned()
            .unwrap_or_else(|| PartitionBounds::new(vec![]));
        // Use the logical null count: a dictionary key whose entry points at a
        // NULL dictionary value is a NULL key even though the key bitmap has no
        // physical nulls (`null_count() == 0` but `logical_null_count() > 0`).
        let keys_have_null = left_data
            .values()
            .iter()
            .any(|array| array.logical_null_count() > 0);

        let build_data = match self.mode {
            PartitionMode::Partitioned => PartitionBuildData::Partitioned {
                partition_id: self.partition,
                pushdown,
                bounds,
                keys_have_null,
            },
            PartitionMode::CollectLeft => PartitionBuildData::CollectLeft {
                pushdown,
                bounds,
                keys_have_null,
            },
            PartitionMode::Auto => unreachable!(
                "PartitionMode::Auto should not be present at execution time. This is a bug in DataFusion, please report it!"
            ),
        };

        self.build_report.schedule(build_data);
        HashJoinStreamState::WaitPartitionBoundsReport
    }

    /// Separate implementation function that unpins the [`HashJoinStream`] so
    /// that partial borrows work correctly
    fn poll_next_impl(
        &mut self,
        cx: &mut std::task::Context<'_>,
    ) -> Poll<Option<Result<RecordBatch>>> {
        loop {
            // First, check if we have any completed batches ready to emit
            if let Some(batch) = self.output_buffer.next_completed_batch() {
                return self
                    .join_metrics
                    .baseline
                    .record_poll(Poll::Ready(Some(Ok(batch))));
            }

            // Check if the coalescer has finished (limit reached and flushed)
            if self.output_buffer.is_finished() {
                return Poll::Ready(None);
            }

            return match self.state {
                HashJoinStreamState::WaitBuildSide => {
                    handle_state!(ready!(self.collect_build_side(cx)))
                }
                HashJoinStreamState::WaitPartitionBoundsReport => {
                    handle_state!(ready!(self.wait_for_partition_bounds_report(cx)))
                }
                HashJoinStreamState::FetchProbeBatch => {
                    handle_state!(ready!(self.fetch_probe_batch(cx)))
                }
                HashJoinStreamState::ProcessProbeBatch(_) => {
                    handle_state!(self.process_probe_batch())
                }
                HashJoinStreamState::ExhaustedProbeSide => {
                    handle_state!(self.prepare_unmatched_build_rows())
                }
                HashJoinStreamState::EmitUnmatchedBuildRows(_) => {
                    handle_state!(self.emit_unmatched_build_rows())
                }
                HashJoinStreamState::Completed if !self.output_buffer.is_empty() => {
                    // Flush any remaining buffered data
                    self.output_buffer.finish()?;
                    // Continue loop to emit the flushed batch
                    continue;
                }
                HashJoinStreamState::Completed => Poll::Ready(None),
            };
        }
    }

    /// Optional step to wait until build-side information (hash maps or bounds) has been reported by all partitions.
    /// This state is only entered if a build accumulator is present.
    ///
    /// ## Why wait?
    ///
    /// The dynamic filter is only built once all partitions have reported their information (hash maps or bounds).
    /// If we do not wait here, the probe-side scan may start before the filter is ready.
    /// This can lead to the probe-side scan missing the opportunity to apply the filter
    /// and skip reading unnecessary data.
    fn wait_for_partition_bounds_report(
        &mut self,
        cx: &mut std::task::Context<'_>,
    ) -> Poll<Result<StatefulStreamResult<Option<RecordBatch>>>> {
        ready!(self.build_report.poll_delivery(cx))?;
        let build_side = self.build_side.try_as_ready()?;
        self.state =
            Self::state_after_build_ready(self.join_type, build_side.left_data.as_ref());
        Poll::Ready(Ok(StatefulStreamResult::Continue))
    }

    /// Collects build-side data by polling `OnceFut` future from initialized build-side
    ///
    /// Updates build-side to `Ready`, and state to `FetchProbeSide`
    fn collect_build_side(
        &mut self,
        cx: &mut std::task::Context<'_>,
    ) -> Poll<Result<StatefulStreamResult<Option<RecordBatch>>>> {
        let build_timer = self.join_metrics.build_time.timer();
        // build hash table from left (build) side, if not yet done
        let left_data = ready!(
            self.build_side
                .try_as_initial_mut()?
                .left_fut
                .get_shared(cx)
        )?;
        build_timer.done();

        // Note: For null-aware anti join, we need to check the probe side (right) for NULLs,
        // not the build side (left). The probe-side NULL check happens during process_probe_batch.
        // The probe_side_has_null flag will be set there if any probe batch contains NULL.

        self.state = self.transition_after_build_collected(&left_data);

        self.build_side = BuildSide::Ready(BuildSideReadyState { left_data });
        Poll::Ready(Ok(StatefulStreamResult::Continue))
    }

    /// Fetches next batch from probe-side
    ///
    /// If non-empty batch has been fetched, updates state to `ProcessProbeBatchState`,
    /// otherwise updates state to `ExhaustedProbeSide`
    fn fetch_probe_batch(
        &mut self,
        cx: &mut std::task::Context<'_>,
    ) -> Poll<Result<StatefulStreamResult<Option<RecordBatch>>>> {
        match ready!(self.right.poll_next_unpin(cx)) {
            None => {
                // Release the probe-side input pipeline's resources. The schema
                // is preserved so callers that still query `self.right.schema()`
                // (e.g. for unmatched-build emission) keep working.
                let right_schema = self.right.schema();
                self.right = Box::pin(EmptyRecordBatchStream::new(right_schema));
                self.state = HashJoinStreamState::ExhaustedProbeSide;
            }
            Some(Ok(batch)) => {
                // Precalculate hash values for fetched batch
                let keys_values = evaluate_expressions_to_arrays(&self.on_right, &batch)?;

                let valid_keys = if let Map::HashMap(_) =
                    self.build_side.try_as_ready()?.left_data.map()
                {
                    self.hashes_buffer.clear();
                    self.hashes_buffer.resize(batch.num_rows(), 0);
                    create_hashes(
                        &keys_values,
                        &self.random_state,
                        &mut self.hashes_buffer,
                    )?;
                    matchable_join_keys(&keys_values, self.null_equality)
                } else {
                    None
                };

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

                self.state =
                    HashJoinStreamState::ProcessProbeBatch(ProcessProbeBatchState {
                        batch,
                        values: keys_values,
                        valid_keys,
                        offset: AtRow { row: 0 },
                        joined_probe_idx: None,
                        matched_probe_idx: None,
                        key_comparator: None,
                    });
            }
            Some(Err(err)) => return Poll::Ready(Err(err)),
        }

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

    /// Joins current probe batch with build-side data and produces batch with matched output
    ///
    /// Updates state to `FetchProbeBatch`
    fn process_probe_batch(
        &mut self,
    ) -> Result<StatefulStreamResult<Option<RecordBatch>>> {
        let state = self.state.try_as_process_probe_batch_mut()?;
        let build_side = self.build_side.try_as_ready_mut()?;

        // A probe batch may be processed in several chunks; count its rows once,
        // on the first chunked lookup (offset == AtRow {row: 0}).
        if state.is_first_chunk() {
            self.join_metrics
                .probe_hit_rate
                .add_total(state.batch.num_rows());
        }

        let timer = self.join_metrics.join_time.timer();

        // Before the empty-build-map return below: a correlated `NOT IN`
        // marks UNKNOWN rows even when every build key is NULL.
        let skip = self.not_in.before_lookup(
            &build_side.left_data,
            &state.batch,
            &state.values,
            state.is_first_chunk(),
            self.filter.as_ref(),
            &self.random_state,
            self.batch_size,
        )?;
        if skip {
            timer.done();
            self.state = HashJoinStreamState::FetchProbeBatch;
            return Ok(StatefulStreamResult::Continue);
        }

        let is_empty = !build_side.left_data.has_matchable_build_rows();

        if is_empty {
            let result = self.not_in.after_empty_build(build_batch_empty_build_side(
                &self.schema,
                build_side.left_data.batch(),
                &state.batch,
                &self.column_indices,
                self.join_type,
            )?)?;
            timer.done();
            self.output_buffer.push_batch(result)?;
            self.state = HashJoinStreamState::FetchProbeBatch;

            return Ok(StatefulStreamResult::Continue);
        }

        // Array map lookups move their index buffers into the arrays below.
        // Keep a handle on those buffers so they can be reused as scratch
        // space once this chunk's output batch is built.
        let mut array_map_buffers = None;

        // get the matched by join keys indices
        let (left_indices, right_indices, next_offset) = match build_side.left_data.map()
        {
            Map::HashMap(map) => lookup_join_hashmap(
                map.as_ref(),
                build_side.left_data.values(),
                &state.values,
                self.null_equality,
                &self.hashes_buffer,
                state.valid_keys.as_ref(),
                self.batch_size,
                state.offset,
                &mut self.probe_indices_buffer,
                &mut self.build_indices_buffer,
                &mut state.key_comparator,
            )?,
            Map::ArrayMap(array_map) => {
                let next_offset = array_map.get_matched_indices_with_limit_offset(
                    &state.values,
                    self.batch_size,
                    state.offset,
                    &mut self.probe_indices_buffer,
                    &mut self.build_indices_buffer,
                )?;
                let build_indices: UInt64Array =
                    std::mem::take(&mut self.build_indices_buffer).into();
                let probe_indices: UInt32Array =
                    std::mem::take(&mut self.probe_indices_buffer).into();
                array_map_buffers = Some((
                    build_indices.values().clone(),
                    probe_indices.values().clone(),
                ));
                (build_indices, probe_indices, next_offset)
            }
        };

        let matched_probe_rows = state.count_new_matched_probe_rows(&right_indices);

        self.join_metrics
            .probe_hit_rate
            .add_part(matched_probe_rows);

        self.join_metrics.avg_fanout.add_part(left_indices.len());

        self.join_metrics.avg_fanout.add_total(matched_probe_rows);

        // apply join filter if exists
        let (left_indices, right_indices) = if let Some(filter) = &self.filter {
            apply_join_filter_to_indices(
                build_side.left_data.batch(),
                &state.batch,
                left_indices,
                right_indices,
                filter,
                JoinSide::Left,
                None,
                self.join_type,
            )?
        } else {
            (left_indices, right_indices)
        };

        // mark joined left-side indices as visited, if required by join type
        if need_produce_result_in_final(self.join_type) {
            let mut bitmap = build_side.left_data.visited_indices_bitmap().lock();
            left_indices.iter().flatten().for_each(|x| {
                bitmap.set_bit(x as usize, true);
            });
        }

        // The goals of index alignment for different join types are:
        //
        // 1) Right & FullJoin -- to append all missing probe-side indices between
        //    previous (excluding) and current joined indices.
        // 2) SemiJoin -- deduplicate probe indices in range between previous
        //    (excluding) and current joined indices.
        // 3) AntiJoin -- return only missing indices in range between
        //    previous and current joined indices.
        //    Inclusion/exclusion of the indices themselves don't matter
        //
        // As a summary -- alignment range can be produced based only on
        // joined (matched with filters applied) probe side indices, excluding starting one
        // (left from previous iteration).

        // if any rows have been joined -- get last joined probe-side (right) row
        // it's important that index counts as "joined" after hash collisions checks
        // and join filters applied.
        let last_joined_right_idx = match right_indices.len() {
            0 => None,
            n => Some(right_indices.value(n - 1) as usize),
        };

        // Calculate range and perform alignment.
        // In case probe batch has been processed -- align all remaining rows.
        let index_alignment_range_start = state.joined_probe_idx.map_or(0, |v| v + 1);
        let index_alignment_range_end = if next_offset.is_none() {
            state.batch.num_rows()
        } else {
            last_joined_right_idx.map_or(0, |v| v + 1)
        };

        let (left_indices, mut right_indices) = adjust_indices_by_join_type(
            left_indices,
            right_indices,
            index_alignment_range_start..index_alignment_range_end,
            self.join_type,
            self.right_side_ordered,
        )?;

        if let Some(not_in) = build_side.left_data.not_in() {
            right_indices = self.not_in.after_lookup(
                not_in,
                &state.values,
                state.valid_keys.as_ref(),
                right_indices,
            );
        }

        // Build output batch and push to coalescer
        let (build_batch, probe_batch, join_side) =
            if self.join_type == JoinType::RightMark {
                (&state.batch, build_side.left_data.batch(), JoinSide::Right)
            } else {
                (build_side.left_data.batch(), &state.batch, JoinSide::Left)
            };

        let batch = build_batch_from_indices(
            &self.schema,
            build_batch,
            probe_batch,
            &left_indices,
            &right_indices,
            &self.column_indices,
            join_side,
            self.join_type,
            None,
        )?;

        // Reclaim the array map scratch buffers now that no index array
        // refers to them.
        drop((left_indices, right_indices));
        if let Some((build_buffer, probe_buffer)) = array_map_buffers {
            self.build_indices_buffer = build_buffer.into();
            self.probe_indices_buffer = probe_buffer.into();
        }

        let push_status = self.output_buffer.push_batch(batch)?;

        timer.done();

        // If limit reached, finish and move to Completed state
        if push_status == PushBatchStatus::LimitReached {
            self.output_buffer.finish()?;
            self.state = HashJoinStreamState::Completed;
            return Ok(StatefulStreamResult::Continue);
        }

        if next_offset.is_none() {
            self.state = HashJoinStreamState::FetchProbeBatch;
        } else {
            state.advance(
                next_offset
                    .ok_or_else(|| internal_datafusion_err!("unexpected None offset"))?,
                last_joined_right_idx,
            )
        }

        Ok(StatefulStreamResult::Continue)
    }

    /// Decides whether this stream emits the final build-side rows (unmatched
    /// rows, or matched rows for `LeftSemi`) once the probe side is exhausted.
    ///
    /// Only the last partition to finish probing emits them, since the shared
    /// visited bitmap is complete only at that point. Updates state to
    /// `EmitUnmatchedBuildRows` when there are rows to emit, and to `Completed`
    /// otherwise.
    fn prepare_unmatched_build_rows(
        &mut self,
    ) -> Result<StatefulStreamResult<Option<RecordBatch>>> {
        let timer = self.join_metrics.join_time.timer();

        if !need_produce_result_in_final(self.join_type) {
            timer.done();
            self.state = HashJoinStreamState::Completed;
            return Ok(StatefulStreamResult::Continue);
        }

        let build_side = self.build_side.try_as_ready()?;

        // Only the last probe partition to finish emits the build-side rows,
        // and only it receives the shared probe-side summary (see
        // `JoinLeftData::report_probe_completed` for why the flags are not
        // readable any other way here).
        let Completion::Emit(probe_summary) =
            build_side.left_data.report_probe_completed()
        else {
            timer.done();
            self.state = HashJoinStreamState::Completed;
            return Ok(StatefulStreamResult::Continue);
        };

        // Every probe partition has finished, so the bitmap is final: snapshot
        // it once and release the lock for the whole emission phase.
        let visited = build_side
            .left_data
            .visited_indices_bitmap()
            .lock()
            .finish_cloned();

        // The final build rows count as one logical input batch; the rows are
        // added chunk by chunk in `emit_unmatched_build_rows`.
        self.join_metrics.input_batches.add(1);

        timer.done();
        self.state =
            HashJoinStreamState::EmitUnmatchedBuildRows(EmitUnmatchedBuildRowsState {
                visited,
                cursor: 0,
                probe_summary,
            });

        Ok(StatefulStreamResult::Continue)
    }

    /// Emits the next chunk of at most `batch_size` final build-side rows and
    /// stays in `EmitUnmatchedBuildRows` until every build row has been
    /// examined, then updates state to `Completed`.
    ///
    /// Emitting in chunks instead of one batch over the whole build side keeps
    /// the output within `batch_size` and bounds the memory materialized at
    /// once, which otherwise grows with the number of unmatched build rows
    /// (e.g. a highly selective `LeftAnti` join over a large build side).
    fn emit_unmatched_build_rows(
        &mut self,
    ) -> Result<StatefulStreamResult<Option<RecordBatch>>> {
        let timer = self.join_metrics.join_time.timer();

        let state = self.state.try_as_emit_unmatched_build_rows_mut()?;
        if state.cursor >= state.visited.len() {
            timer.done();
            self.state = HashJoinStreamState::Completed;
            return Ok(StatefulStreamResult::Continue);
        }

        let build_side = self.build_side.try_as_ready()?;

        let probe_summary = state.probe_summary;

        // use the global left bitmap to produce the left indices and right indices
        let (left_side, right_side) = next_final_indices_chunk(
            &state.visited,
            &mut state.cursor,
            self.join_type,
            self.batch_size,
        );

        let (left_side, right_side, mark_column) = match build_side.left_data.not_in() {
            Some(not_in) => not_in.final_chunk(probe_summary, left_side, right_side),
            None => (left_side, right_side, None),
        };

        self.join_metrics.input_rows.add(left_side.len());

        // Push this chunk of final indices to output buffer
        if !left_side.is_empty() {
            let empty_right_batch = RecordBatch::new_empty(self.right.schema());
            let batch = build_batch_from_indices(
                &self.schema,
                build_side.left_data.batch(),
                &empty_right_batch,
                &left_side,
                &right_side,
                &self.column_indices,
                JoinSide::Left,
                self.join_type,
                mark_column.as_ref(),
            )?;
            let push_status = self.output_buffer.push_batch(batch)?;

            // If limit reached, finish the coalescer and stop emitting
            if push_status == PushBatchStatus::LimitReached {
                self.output_buffer.finish()?;
                self.state = HashJoinStreamState::Completed;
            }
        }

        timer.done();

        Ok(StatefulStreamResult::Continue)
    }
}

/// Returns the next chunk of final build-side indices for join types that
/// produce build rows once the probe side is exhausted, starting at `cursor`
/// and holding at most `batch_size` rows. Advances `cursor` past the build
/// rows examined; `cursor == visited.len()` means every row has been examined.
///
/// The build indices are always valid. The probe indices are NULL for every
/// row (`Left`, `LeftAnti`, `Full`, `LeftSemi`), except for `LeftMark`, where
/// every build row is emitted and a NULL probe index marks an unmatched row.
///
/// For example, with `visited = [true, false, true, true, false]`:
/// - `Left`: build `[1, 4]`, probe `[null, null]`
/// - `LeftSemi`: build `[0, 2, 3]`, probe `[null, null, null]`
/// - `LeftMark`: build `[0, 1, 2, 3, 4]`, probe `[0, null, 0, 0, null]`
fn next_final_indices_chunk(
    visited: &BooleanBuffer,
    cursor: &mut usize,
    join_type: JoinType,
    batch_size: usize,
) -> (UInt64Array, UInt32Array) {
    let num_rows = visited.len();
    let start = *cursor;

    if join_type == JoinType::LeftMark {
        // Every build row is emitted, so a chunk is a plain range of rows.
        let end = (start + batch_size).min(num_rows);
        let build_indices = (start as u64..end as u64).collect::<UInt64Array>();
        let probe_indices = (start..end)
            .map(|idx| visited.value(idx).then_some(0))
            .collect::<UInt32Array>();
        *cursor = end;
        return (build_indices, probe_indices);
    }

    // `LeftSemi` emits the matched build rows; `Left`, `LeftAnti` and `Full`
    // emit the unmatched ones.
    let emit_visited = join_type == JoinType::LeftSemi;
    let mut build_indices = Vec::with_capacity(batch_size.min(num_rows - start));
    let mut idx = start;
    while idx < num_rows && build_indices.len() < batch_size {
        if visited.value(idx) == emit_visited {
            build_indices.push(idx as u64);
        }
        idx += 1;
    }
    *cursor = idx;

    let probe_indices = UInt32Array::new_null(build_indices.len());
    (UInt64Array::from(build_indices), probe_indices)
}

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

    fn poll_next(
        mut self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> Poll<Option<Self::Item>> {
        self.poll_next_impl(cx)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::joins::hash_join::shared_bounds::{
        PushdownStrategy, completed_partitions_for_test,
        make_partitioned_accumulator_for_test,
    };

    fn empty_build_data(partition_id: usize) -> PartitionBuildData {
        PartitionBuildData::Partitioned {
            partition_id,
            pushdown: PushdownStrategy::Empty,
            bounds: PartitionBounds::new(vec![]),
            keys_have_null: false,
        }
    }

    fn partitioned_handle(acc: &Arc<SharedBuildAccumulator>) -> BuildReportHandle {
        BuildReportHandle::new(0, PartitionMode::Partitioned, Some(Arc::clone(acc)))
    }

    #[test]
    fn build_report_handle_cancels_scheduled_partition_on_drop() {
        let acc = Arc::new(make_partitioned_accumulator_for_test(2));

        {
            let mut handle = partitioned_handle(&acc);
            handle.schedule(empty_build_data(0));
            assert_eq!(handle.state(), &BuildReportState::Scheduled);
        }

        assert_eq!(completed_partitions_for_test(&acc), 1);
    }

    #[test]
    fn build_report_handle_does_not_cancel_delivered_partition_on_drop() {
        let acc = Arc::new(make_partitioned_accumulator_for_test(1));

        {
            let mut handle = partitioned_handle(&acc);
            handle.schedule(empty_build_data(0));
            let mut cx = std::task::Context::from_waker(futures::task::noop_waker_ref());
            assert!(matches!(handle.poll_delivery(&mut cx), Poll::Ready(Ok(()))));
            assert_eq!(handle.state(), &BuildReportState::Delivered);
        }

        assert_eq!(completed_partitions_for_test(&acc), 1);
    }

    #[test]
    fn build_report_handle_cancel_pending_is_idempotent() {
        let acc = Arc::new(make_partitioned_accumulator_for_test(2));
        let mut handle = partitioned_handle(&acc);
        handle.schedule(empty_build_data(0));

        handle.cancel_pending();
        handle.cancel_pending();

        assert_eq!(handle.state(), &BuildReportState::Canceled);
        assert_eq!(completed_partitions_for_test(&acc), 1);
    }

    #[test]
    fn build_report_handle_no_accumulator_finalizes() {
        let mut handle = BuildReportHandle::new(0, PartitionMode::Partitioned, None);

        handle.schedule(empty_build_data(0));
        handle.cancel_pending();

        assert_eq!(handle.state(), &BuildReportState::Finalized);
    }
}