forked from apache/datafusion
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathexec.rs
More file actions
5640 lines (5045 loc) · 201 KB
/
exec.rs
File metadata and controls
5640 lines (5045 loc) · 201 KB
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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
use std::fmt;
use std::mem::size_of;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, OnceLock};
use std::{any::Any, vec};
use crate::ExecutionPlanProperties;
use crate::execution_plan::{EmissionType, boundedness_from_children};
use crate::filter_pushdown::{
ChildPushdownResult, FilterDescription, FilterPushdownPhase,
FilterPushdownPropagation,
};
use crate::joins::Map;
use crate::joins::array_map::ArrayMap;
use crate::joins::hash_join::inlist_builder::build_struct_inlist_values;
use crate::joins::hash_join::shared_bounds::{
ColumnBounds, PartitionBounds, PushdownStrategy, SharedBuildAccumulator,
};
use crate::joins::hash_join::stream::{
BuildSide, BuildSideInitialState, HashJoinStream, HashJoinStreamState,
};
use crate::joins::join_hash_map::{JoinHashMapU32, JoinHashMapU64};
use crate::joins::utils::{
OnceAsync, OnceFut, asymmetric_join_output_partitioning, reorder_output_after_swap,
swap_join_projection, update_hash,
};
use crate::joins::{JoinOn, JoinOnRef, PartitionMode, SharedBitmapBuilder};
use crate::metrics::{Count, MetricBuilder};
use crate::projection::{
EmbeddedProjection, JoinData, ProjectionExec, try_embed_projection,
try_pushdown_through_join,
};
use crate::repartition::REPARTITION_RANDOM_STATE;
use crate::spill::get_record_batch_memory_size;
use crate::{
DisplayAs, DisplayFormatType, Distribution, ExecutionPlan, Partitioning,
PlanProperties, SendableRecordBatchStream, Statistics,
common::can_project,
joins::utils::{
BuildProbeJoinMetrics, ColumnIndex, JoinFilter, JoinHashMapType,
build_join_schema, check_join_is_valid, estimate_join_statistics,
need_produce_result_in_final, symmetric_join_output_partitioning,
},
metrics::{ExecutionPlanMetricsSet, MetricsSet},
};
use arrow::array::{ArrayRef, BooleanBufferBuilder};
use arrow::compute::concat_batches;
use arrow::datatypes::SchemaRef;
use arrow::record_batch::RecordBatch;
use arrow::util::bit_util;
use arrow_schema::DataType;
use datafusion_common::config::ConfigOptions;
use datafusion_common::utils::memory::estimate_memory_size;
use datafusion_common::{
JoinSide, JoinType, NullEquality, Result, assert_or_internal_err, internal_err,
plan_err, project_schema,
};
use datafusion_execution::TaskContext;
use datafusion_execution::memory_pool::{MemoryConsumer, MemoryReservation};
use datafusion_expr::Accumulator;
use datafusion_functions_aggregate_common::min_max::{MaxAccumulator, MinAccumulator};
use datafusion_physical_expr::equivalence::{
ProjectionMapping, join_equivalence_properties,
};
use datafusion_physical_expr::expressions::{DynamicFilterPhysicalExpr, lit};
use datafusion_physical_expr::{PhysicalExpr, PhysicalExprRef};
use ahash::RandomState;
use datafusion_physical_expr_common::physical_expr::fmt_sql;
use datafusion_physical_expr_common::utils::evaluate_expressions_to_arrays;
use futures::TryStreamExt;
use parking_lot::Mutex;
use super::partitioned_hash_eval::SeededRandomState;
/// Hard-coded seed to ensure hash values from the hash join differ from `RepartitionExec`, avoiding collisions.
pub(crate) const HASH_JOIN_SEED: SeededRandomState =
SeededRandomState::with_seeds('J' as u64, 'O' as u64, 'I' as u64, 'N' as u64);
const ARRAY_MAP_CREATED_COUNT_METRIC_NAME: &str = "array_map_created_count";
#[expect(clippy::too_many_arguments)]
fn try_create_array_map(
bounds: &Option<PartitionBounds>,
schema: &SchemaRef,
batches: &[RecordBatch],
on_left: &[PhysicalExprRef],
reservation: &mut MemoryReservation,
perfect_hash_join_small_build_threshold: usize,
perfect_hash_join_min_key_density: f64,
null_equality: NullEquality,
) -> Result<Option<(ArrayMap, RecordBatch, Vec<ArrayRef>)>> {
if on_left.len() != 1 {
return Ok(None);
}
if null_equality == NullEquality::NullEqualsNull {
for batch in batches.iter() {
let arrays = evaluate_expressions_to_arrays(on_left, batch)?;
if arrays[0].null_count() > 0 {
return Ok(None);
}
}
}
let (min_val, max_val) = if let Some(bounds) = bounds {
let (min_val, max_val) = if let Some(cb) = bounds.get_column_bounds(0) {
(cb.min.clone(), cb.max.clone())
} else {
return Ok(None);
};
if min_val.is_null() || max_val.is_null() {
return Ok(None);
}
if min_val > max_val {
return internal_err!("min_val>max_val");
}
if let Some((mi, ma)) =
ArrayMap::key_to_u64(&min_val).zip(ArrayMap::key_to_u64(&max_val))
{
(mi, ma)
} else {
return Ok(None);
}
} else {
return Ok(None);
};
let range = ArrayMap::calculate_range(min_val, max_val);
let num_row: usize = batches.iter().map(|x| x.num_rows()).sum();
let dense_ratio = (num_row as f64) / ((range + 1) as f64);
// TODO: support create ArrayMap<u64>
if num_row >= u32::MAX as usize {
return Ok(None);
}
if range >= perfect_hash_join_small_build_threshold as u64
&& dense_ratio <= perfect_hash_join_min_key_density
{
return Ok(None);
}
// If range equals usize::MAX, then range + 1 would overflow to 0, which would cause
// ArrayMap to allocate an invalid zero-sized array or cause indexing issues.
// This check prevents such overflow and ensures valid array allocation.
if range == usize::MAX as u64 {
return Ok(None);
}
let mem_size = ArrayMap::estimate_memory_size(min_val, max_val, num_row);
reservation.try_grow(mem_size)?;
let batch = concat_batches(schema, batches)?;
let left_values = evaluate_expressions_to_arrays(on_left, &batch)?;
let array_map = ArrayMap::try_new(&left_values[0], min_val, max_val)?;
Ok(Some((array_map, batch, left_values)))
}
/// HashTable and input data for the left (build side) of a join
pub(super) struct JoinLeftData {
/// The hash table with indices into `batch`
/// Arc is used to allow sharing with SharedBuildAccumulator for hash map pushdown
pub(super) map: Arc<Map>,
/// The input rows for the build side
batch: RecordBatch,
/// The build side on expressions values
values: Vec<ArrayRef>,
/// Shared bitmap builder for visited left indices
visited_indices_bitmap: SharedBitmapBuilder,
/// Counter of running probe-threads, potentially
/// able to update `visited_indices_bitmap`
probe_threads_counter: AtomicUsize,
/// We need to keep this field to maintain accurate memory accounting, even though we don't directly use it.
/// Without holding onto this reservation, the recorded memory usage would become inconsistent with actual usage.
/// This could hide potential out-of-memory issues, especially when upstream operators increase their memory consumption.
/// The MemoryReservation ensures proper tracking of memory resources throughout the join operation's lifecycle.
_reservation: MemoryReservation,
/// Bounds computed from the build side for dynamic filter pushdown.
/// If the partition is empty (no rows) this will be None.
/// If the partition has some rows this will be Some with the bounds for each join key column.
pub(super) bounds: Option<PartitionBounds>,
/// Membership testing strategy for filter pushdown
/// Contains either InList values for small build sides or hash table reference for large build sides
pub(super) membership: PushdownStrategy,
/// Shared atomic flag indicating if any probe partition saw data (for null-aware anti joins)
/// This is shared across all probe partitions to provide global knowledge
pub(super) probe_side_non_empty: AtomicBool,
/// Shared atomic flag indicating if any probe partition saw NULL in join keys (for null-aware anti joins)
pub(super) probe_side_has_null: AtomicBool,
}
impl JoinLeftData {
/// return a reference to the map
pub(super) fn map(&self) -> &Map {
&self.map
}
/// returns a reference to the build side batch
pub(super) fn batch(&self) -> &RecordBatch {
&self.batch
}
/// returns a reference to the build side expressions values
pub(super) fn values(&self) -> &[ArrayRef] {
&self.values
}
/// returns a reference to the visited indices bitmap
pub(super) fn visited_indices_bitmap(&self) -> &SharedBitmapBuilder {
&self.visited_indices_bitmap
}
/// returns a reference to the InList values for filter pushdown
pub(super) fn membership(&self) -> &PushdownStrategy {
&self.membership
}
/// Decrements the counter of running threads, and returns `true`
/// if caller is the last running thread
pub(super) fn report_probe_completed(&self) -> bool {
self.probe_threads_counter.fetch_sub(1, Ordering::Relaxed) == 1
}
}
#[expect(rustdoc::private_intra_doc_links)]
/// Join execution plan: Evaluates equijoin predicates in parallel on multiple
/// partitions using a hash table and an optional filter list to apply post
/// join.
///
/// # Join Expressions
///
/// This implementation is optimized for evaluating equijoin predicates (
/// `<col1> = <col2>`) expressions, which are represented as a list of `Columns`
/// in [`Self::on`].
///
/// Non-equality predicates, which can not pushed down to a join inputs (e.g.
/// `<col1> != <col2>`) are known as "filter expressions" and are evaluated
/// after the equijoin predicates.
///
/// # ArrayMap Optimization
///
/// For joins with a single integer-based join key, `HashJoinExec` may use an [`ArrayMap`]
/// (also known as a "perfect hash join") instead of a general-purpose hash map.
/// This optimization is used when:
/// 1. There is exactly one join key.
/// 2. The join key is an integer type up to 64 bits wide that can be losslessly converted
/// to `u64` (128-bit integer types such as `i128` and `u128` are not supported).
/// 3. The range of keys is small enough (controlled by `perfect_hash_join_small_build_threshold`)
/// OR the keys are sufficiently dense (controlled by `perfect_hash_join_min_key_density`).
/// 4. build_side.num_rows() < u32::MAX
/// 5. NullEqualsNothing || (NullEqualsNull && build side doesn't contain null)
///
/// See [`try_create_array_map`] for more details.
///
/// Note that when using [`PartitionMode::Partitioned`], the build side is split into multiple
/// partitions. This can cause a dense build side to become sparse within each partition,
/// potentially disabling this optimization.
///
/// For example, consider:
/// ```sql
/// SELECT t1.value, t2.value
/// FROM range(10000) AS t1
/// JOIN range(10000) AS t2
/// ON t1.value = t2.value;
/// ```
/// With 24 partitions, each partition will only receive a subset of the 10,000 rows.
/// The first partition might contain values like `3, 10, 18, 39, 43`, which are sparse
/// relative to the original range, even though the overall data set is dense.
///
/// # "Build Side" vs "Probe Side"
///
/// HashJoin takes two inputs, which are referred to as the "build" and the
/// "probe". The build side is the first child, and the probe side is the second
/// child.
///
/// The two inputs are treated differently and it is VERY important that the
/// *smaller* input is placed on the build side to minimize the work of creating
/// the hash table.
///
/// ```text
/// ┌───────────┐
/// │ HashJoin │
/// │ │
/// └───────────┘
/// │ │
/// ┌─────┘ └─────┐
/// ▼ ▼
/// ┌────────────┐ ┌─────────────┐
/// │ Input │ │ Input │
/// │ [0] │ │ [1] │
/// └────────────┘ └─────────────┘
///
/// "build side" "probe side"
/// ```
///
/// Execution proceeds in 2 stages:
///
/// 1. the **build phase** creates a hash table from the tuples of the build side,
/// and single concatenated batch containing data from all fetched record batches.
/// Resulting hash table stores hashed join-key fields for each row as a key, and
/// indices of corresponding rows in concatenated batch.
///
/// When using the standard `JoinHashMap`, hash join uses LIFO data structure as a hash table,
/// and in order to retain original build-side input order while obtaining data during probe phase,
/// hash table is updated by iterating batch sequence in reverse order -- it allows to
/// keep rows with smaller indices "on the top" of hash table, and still maintain
/// correct indexing for concatenated build-side data batch.
///
/// Example of build phase for 3 record batches:
///
///
/// ```text
///
/// Original build-side data Inserting build-side values into hashmap Concatenated build-side batch
/// ┌───────────────────────────┐
/// hashmap.insert(row-hash, row-idx + offset) │ idx │
/// ┌───────┐ │ ┌───────┐ │
/// │ Row 1 │ 1) update_hash for batch 3 with offset 0 │ │ Row 6 │ 0 │
/// Batch 1 │ │ - hashmap.insert(Row 7, idx 1) │ Batch 3 │ │ │
/// │ Row 2 │ - hashmap.insert(Row 6, idx 0) │ │ Row 7 │ 1 │
/// └───────┘ │ └───────┘ │
/// │ │
/// ┌───────┐ │ ┌───────┐ │
/// │ Row 3 │ 2) update_hash for batch 2 with offset 2 │ │ Row 3 │ 2 │
/// │ │ - hashmap.insert(Row 5, idx 4) │ │ │ │
/// Batch 2 │ Row 4 │ - hashmap.insert(Row 4, idx 3) │ Batch 2 │ Row 4 │ 3 │
/// │ │ - hashmap.insert(Row 3, idx 2) │ │ │ │
/// │ Row 5 │ │ │ Row 5 │ 4 │
/// └───────┘ │ └───────┘ │
/// │ │
/// ┌───────┐ │ ┌───────┐ │
/// │ Row 6 │ 3) update_hash for batch 1 with offset 5 │ │ Row 1 │ 5 │
/// Batch 3 │ │ - hashmap.insert(Row 2, idx 6) │ Batch 1 │ │ │
/// │ Row 7 │ - hashmap.insert(Row 1, idx 5) │ │ Row 2 │ 6 │
/// └───────┘ │ └───────┘ │
/// │ │
/// └───────────────────────────┘
/// ```
///
/// 2. the **probe phase** where the tuples of the probe side are streamed
/// through, checking for matches of the join keys in the hash table.
///
/// ```text
/// ┌────────────────┐ ┌────────────────┐
/// │ ┌─────────┐ │ │ ┌─────────┐ │
/// │ │ Hash │ │ │ │ Hash │ │
/// │ │ Table │ │ │ │ Table │ │
/// │ │(keys are│ │ │ │(keys are│ │
/// │ │equi join│ │ │ │equi join│ │ Stage 2: batches from
/// Stage 1: the │ │columns) │ │ │ │columns) │ │ the probe side are
/// *entire* build │ │ │ │ │ │ │ │ streamed through, and
/// side is read │ └─────────┘ │ │ └─────────┘ │ checked against the
/// into the hash │ ▲ │ │ ▲ │ contents of the hash
/// table │ HashJoin │ │ HashJoin │ table
/// └──────┼─────────┘ └──────────┼─────┘
/// ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─
/// │ │
///
/// │ │
/// ┌────────────┐ ┌────────────┐
/// │RecordBatch │ │RecordBatch │
/// └────────────┘ └────────────┘
/// ┌────────────┐ ┌────────────┐
/// │RecordBatch │ │RecordBatch │
/// └────────────┘ └────────────┘
/// ... ...
/// ┌────────────┐ ┌────────────┐
/// │RecordBatch │ │RecordBatch │
/// └────────────┘ └────────────┘
///
/// build side probe side
/// ```
///
/// # Example "Optimal" Plans
///
/// The differences in the inputs means that for classic "Star Schema Query",
/// the optimal plan will be a **"Right Deep Tree"** . A Star Schema Query is
/// one where there is one large table and several smaller "dimension" tables,
/// joined on `Foreign Key = Primary Key` predicates.
///
/// A "Right Deep Tree" looks like this large table as the probe side on the
/// lowest join:
///
/// ```text
/// ┌───────────┐
/// │ HashJoin │
/// │ │
/// └───────────┘
/// │ │
/// ┌───────┘ └──────────┐
/// ▼ ▼
/// ┌───────────────┐ ┌───────────┐
/// │ small table 1 │ │ HashJoin │
/// │ "dimension" │ │ │
/// └───────────────┘ └───┬───┬───┘
/// ┌──────────┘ └───────┐
/// │ │
/// ▼ ▼
/// ┌───────────────┐ ┌───────────┐
/// │ small table 2 │ │ HashJoin │
/// │ "dimension" │ │ │
/// └───────────────┘ └───┬───┬───┘
/// ┌────────┘ └────────┐
/// │ │
/// ▼ ▼
/// ┌───────────────┐ ┌───────────────┐
/// │ small table 3 │ │ large table │
/// │ "dimension" │ │ "fact" │
/// └───────────────┘ └───────────────┘
/// ```
///
/// # Clone / Shared State
///
/// Note this structure includes a [`OnceAsync`] that is used to coordinate the
/// loading of the left side with the processing in each output stream.
/// Therefore it can not be [`Clone`]
pub struct HashJoinExec {
/// left (build) side which gets hashed
pub left: Arc<dyn ExecutionPlan>,
/// right (probe) side which are filtered by the hash table
pub right: Arc<dyn ExecutionPlan>,
/// Set of equijoin columns from the relations: `(left_col, right_col)`
pub on: Vec<(PhysicalExprRef, PhysicalExprRef)>,
/// Filters which are applied while finding matching rows
pub filter: Option<JoinFilter>,
/// How the join is performed (`OUTER`, `INNER`, etc)
pub join_type: JoinType,
/// The schema after join. Please be careful when using this schema,
/// if there is a projection, the schema isn't the same as the output schema.
join_schema: SchemaRef,
/// Future that consumes left input and builds the hash table
///
/// For CollectLeft partition mode, this structure is *shared* across all output streams.
///
/// Each output stream waits on the `OnceAsync` to signal the completion of
/// the hash table creation.
left_fut: Arc<OnceAsync<JoinLeftData>>,
/// Shared the `SeededRandomState` for the hashing algorithm (seeds preserved for serialization)
random_state: SeededRandomState,
/// Partitioning mode to use
pub mode: PartitionMode,
/// Execution metrics
metrics: ExecutionPlanMetricsSet,
/// The projection indices of the columns in the output schema of join
pub projection: Option<Vec<usize>>,
/// Information of index and left / right placement of columns
column_indices: Vec<ColumnIndex>,
/// The equality null-handling behavior of the join algorithm.
pub null_equality: NullEquality,
/// Flag to indicate if this is a null-aware anti join
pub null_aware: bool,
/// Cache holding plan properties like equivalences, output partitioning etc.
cache: PlanProperties,
/// Dynamic filter for pushing down to the probe side
/// Set when dynamic filter pushdown is detected in handle_child_pushdown_result.
/// HashJoinExec also needs to keep a shared bounds accumulator for coordinating updates.
dynamic_filter: Option<HashJoinExecDynamicFilter>,
}
#[derive(Clone)]
struct HashJoinExecDynamicFilter {
/// Dynamic filter that we'll update with the results of the build side once that is done.
filter: Arc<DynamicFilterPhysicalExpr>,
/// Build accumulator to collect build-side information (hash maps and/or bounds) from each partition.
/// It is lazily initialized during execution to make sure we use the actual execution time partition counts.
build_accumulator: OnceLock<Arc<SharedBuildAccumulator>>,
}
impl fmt::Debug for HashJoinExec {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("HashJoinExec")
.field("left", &self.left)
.field("right", &self.right)
.field("on", &self.on)
.field("filter", &self.filter)
.field("join_type", &self.join_type)
.field("join_schema", &self.join_schema)
.field("left_fut", &self.left_fut)
.field("random_state", &self.random_state)
.field("mode", &self.mode)
.field("metrics", &self.metrics)
.field("projection", &self.projection)
.field("column_indices", &self.column_indices)
.field("null_equality", &self.null_equality)
.field("cache", &self.cache)
// Explicitly exclude dynamic_filter to avoid runtime state differences in tests
.finish()
}
}
impl EmbeddedProjection for HashJoinExec {
fn with_projection(&self, projection: Option<Vec<usize>>) -> Result<Self> {
self.with_projection(projection)
}
}
impl HashJoinExec {
/// Tries to create a new [HashJoinExec].
///
/// # Error
/// This function errors when it is not possible to join the left and right sides on keys `on`.
#[expect(clippy::too_many_arguments)]
pub fn try_new(
left: Arc<dyn ExecutionPlan>,
right: Arc<dyn ExecutionPlan>,
on: JoinOn,
filter: Option<JoinFilter>,
join_type: &JoinType,
projection: Option<Vec<usize>>,
partition_mode: PartitionMode,
null_equality: NullEquality,
null_aware: bool,
) -> Result<Self> {
let left_schema = left.schema();
let right_schema = right.schema();
if on.is_empty() {
return plan_err!("On constraints in HashJoinExec should be non-empty");
}
check_join_is_valid(&left_schema, &right_schema, &on)?;
// Validate null_aware flag
if null_aware {
if !matches!(join_type, JoinType::LeftAnti) {
return plan_err!(
"null_aware can only be true for LeftAnti joins, got {join_type}"
);
}
if on.len() != 1 {
return plan_err!(
"null_aware anti join only supports single column join key, got {} columns",
on.len()
);
}
}
let (join_schema, column_indices) =
build_join_schema(&left_schema, &right_schema, join_type);
let random_state = HASH_JOIN_SEED;
let join_schema = Arc::new(join_schema);
// check if the projection is valid
can_project(&join_schema, projection.as_ref())?;
let cache = Self::compute_properties(
&left,
&right,
&join_schema,
*join_type,
&on,
partition_mode,
projection.as_ref(),
)?;
// Initialize both dynamic filter and bounds accumulator to None
// They will be set later if dynamic filtering is enabled
Ok(HashJoinExec {
left,
right,
on,
filter,
join_type: *join_type,
join_schema,
left_fut: Default::default(),
random_state,
mode: partition_mode,
metrics: ExecutionPlanMetricsSet::new(),
projection,
column_indices,
null_equality,
null_aware,
cache,
dynamic_filter: None,
})
}
fn create_dynamic_filter(on: &JoinOn) -> Arc<DynamicFilterPhysicalExpr> {
// Extract the right-side keys (probe side keys) from the `on` clauses
// Dynamic filter will be created from build side values (left side) and applied to probe side (right side)
let right_keys: Vec<_> = on.iter().map(|(_, r)| Arc::clone(r)).collect();
// Initialize with a placeholder expression (true) that will be updated when the hash table is built
Arc::new(DynamicFilterPhysicalExpr::new(right_keys, lit(true)))
}
/// left (build) side which gets hashed
pub fn left(&self) -> &Arc<dyn ExecutionPlan> {
&self.left
}
/// right (probe) side which are filtered by the hash table
pub fn right(&self) -> &Arc<dyn ExecutionPlan> {
&self.right
}
/// Set of common columns used to join on
pub fn on(&self) -> &[(PhysicalExprRef, PhysicalExprRef)] {
&self.on
}
/// Filters applied before join output
pub fn filter(&self) -> Option<&JoinFilter> {
self.filter.as_ref()
}
/// How the join is performed
pub fn join_type(&self) -> &JoinType {
&self.join_type
}
/// The schema after join. Please be careful when using this schema,
/// if there is a projection, the schema isn't the same as the output schema.
pub fn join_schema(&self) -> &SchemaRef {
&self.join_schema
}
/// The partitioning mode of this hash join
pub fn partition_mode(&self) -> &PartitionMode {
&self.mode
}
/// Get null_equality
pub fn null_equality(&self) -> NullEquality {
self.null_equality
}
/// Get the dynamic filter expression for testing purposes.
/// Returns `None` if no dynamic filter has been set.
///
/// This method is intended for testing only and should not be used in production code.
#[doc(hidden)]
pub fn dynamic_filter_for_test(&self) -> Option<&Arc<DynamicFilterPhysicalExpr>> {
self.dynamic_filter.as_ref().map(|df| &df.filter)
}
/// Calculate order preservation flags for this hash join.
fn maintains_input_order(join_type: JoinType) -> Vec<bool> {
vec![
false,
matches!(
join_type,
JoinType::Inner
| JoinType::Right
| JoinType::RightAnti
| JoinType::RightSemi
| JoinType::RightMark
),
]
}
/// Get probe side information for the hash join.
pub fn probe_side() -> JoinSide {
// In current implementation right side is always probe side.
JoinSide::Right
}
/// Return whether the join contains a projection
pub fn contains_projection(&self) -> bool {
self.projection.is_some()
}
/// Return new instance of [HashJoinExec] with the given projection.
pub fn with_projection(&self, projection: Option<Vec<usize>>) -> Result<Self> {
// check if the projection is valid
can_project(&self.schema(), projection.as_ref())?;
let projection = match projection {
Some(projection) => match &self.projection {
Some(p) => Some(projection.iter().map(|i| p[*i]).collect()),
None => Some(projection),
},
None => None,
};
Self::try_new(
Arc::clone(&self.left),
Arc::clone(&self.right),
self.on.clone(),
self.filter.clone(),
&self.join_type,
projection,
self.mode,
self.null_equality,
self.null_aware,
)
}
/// This function creates the cache object that stores the plan properties such as schema, equivalence properties, ordering, partitioning, etc.
fn compute_properties(
left: &Arc<dyn ExecutionPlan>,
right: &Arc<dyn ExecutionPlan>,
schema: &SchemaRef,
join_type: JoinType,
on: JoinOnRef,
mode: PartitionMode,
projection: Option<&Vec<usize>>,
) -> Result<PlanProperties> {
// Calculate equivalence properties:
let mut eq_properties = join_equivalence_properties(
left.equivalence_properties().clone(),
right.equivalence_properties().clone(),
&join_type,
Arc::clone(schema),
&Self::maintains_input_order(join_type),
Some(Self::probe_side()),
on,
)?;
let mut output_partitioning = match mode {
PartitionMode::CollectLeft => {
asymmetric_join_output_partitioning(left, right, &join_type)?
}
PartitionMode::Auto => Partitioning::UnknownPartitioning(
right.output_partitioning().partition_count(),
),
PartitionMode::Partitioned => {
symmetric_join_output_partitioning(left, right, &join_type)?
}
};
let emission_type = if left.boundedness().is_unbounded() {
EmissionType::Final
} else if right.pipeline_behavior() == EmissionType::Incremental {
match join_type {
// If we only need to generate matched rows from the probe side,
// we can emit rows incrementally.
JoinType::Inner
| JoinType::LeftSemi
| JoinType::RightSemi
| JoinType::Right
| JoinType::RightAnti
| JoinType::RightMark => EmissionType::Incremental,
// If we need to generate unmatched rows from the *build side*,
// we need to emit them at the end.
JoinType::Left
| JoinType::LeftAnti
| JoinType::LeftMark
| JoinType::Full => EmissionType::Both,
}
} else {
right.pipeline_behavior()
};
// If contains projection, update the PlanProperties.
if let Some(projection) = projection {
// construct a map from the input expressions to the output expression of the Projection
let projection_mapping = ProjectionMapping::from_indices(projection, schema)?;
let out_schema = project_schema(schema, Some(projection))?;
output_partitioning =
output_partitioning.project(&projection_mapping, &eq_properties);
eq_properties = eq_properties.project(&projection_mapping, out_schema);
}
Ok(PlanProperties::new(
eq_properties,
output_partitioning,
emission_type,
boundedness_from_children([left, right]),
))
}
/// Returns a new `ExecutionPlan` that computes the same join as this one,
/// with the left and right inputs swapped using the specified
/// `partition_mode`.
///
/// # Notes:
///
/// This function is public so other downstream projects can use it to
/// construct `HashJoinExec` with right side as the build side.
///
/// For using this interface directly, please refer to below:
///
/// Hash join execution may require specific input partitioning (for example,
/// the left child may have a single partition while the right child has multiple).
///
/// Calling this function on join nodes whose children have already been repartitioned
/// (e.g., after a `RepartitionExec` has been inserted) may break the partitioning
/// requirements of the hash join. Therefore, ensure you call this function
/// before inserting any repartitioning operators on the join's children.
///
/// In DataFusion's default SQL interface, this function is used by the `JoinSelection`
/// physical optimizer rule to determine a good join order, which is
/// executed before the `EnforceDistribution` rule (the rule that may
/// insert `RepartitionExec` operators).
pub fn swap_inputs(
&self,
partition_mode: PartitionMode,
) -> Result<Arc<dyn ExecutionPlan>> {
let left = self.left();
let right = self.right();
let new_join = HashJoinExec::try_new(
Arc::clone(right),
Arc::clone(left),
self.on()
.iter()
.map(|(l, r)| (Arc::clone(r), Arc::clone(l)))
.collect(),
self.filter().map(JoinFilter::swap),
&self.join_type().swap(),
swap_join_projection(
left.schema().fields().len(),
right.schema().fields().len(),
self.projection.as_ref(),
self.join_type(),
),
partition_mode,
self.null_equality(),
self.null_aware,
)?;
// In case of anti / semi joins or if there is embedded projection in HashJoinExec, output column order is preserved, no need to add projection again
if matches!(
self.join_type(),
JoinType::LeftSemi
| JoinType::RightSemi
| JoinType::LeftAnti
| JoinType::RightAnti
| JoinType::LeftMark
| JoinType::RightMark
) || self.projection.is_some()
{
Ok(Arc::new(new_join))
} else {
reorder_output_after_swap(Arc::new(new_join), &left.schema(), &right.schema())
}
}
}
impl DisplayAs for HashJoinExec {
fn fmt_as(&self, t: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result {
match t {
DisplayFormatType::Default | DisplayFormatType::Verbose => {
let display_filter = self.filter.as_ref().map_or_else(
|| "".to_string(),
|f| format!(", filter={}", f.expression()),
);
let display_projections = if self.contains_projection() {
format!(
", projection=[{}]",
self.projection
.as_ref()
.unwrap()
.iter()
.map(|index| format!(
"{}@{}",
self.join_schema.fields().get(*index).unwrap().name(),
index
))
.collect::<Vec<_>>()
.join(", ")
)
} else {
"".to_string()
};
let display_null_equality =
if matches!(self.null_equality(), NullEquality::NullEqualsNull) {
", NullsEqual: true"
} else {
""
};
let on = self
.on
.iter()
.map(|(c1, c2)| format!("({c1}, {c2})"))
.collect::<Vec<String>>()
.join(", ");
write!(
f,
"HashJoinExec: mode={:?}, join_type={:?}, on=[{}]{}{}{}",
self.mode,
self.join_type,
on,
display_filter,
display_projections,
display_null_equality,
)
}
DisplayFormatType::TreeRender => {
let on = self
.on
.iter()
.map(|(c1, c2)| {
format!("({} = {})", fmt_sql(c1.as_ref()), fmt_sql(c2.as_ref()))
})
.collect::<Vec<String>>()
.join(", ");
if *self.join_type() != JoinType::Inner {
writeln!(f, "join_type={:?}", self.join_type)?;
}
writeln!(f, "on={on}")?;
if matches!(self.null_equality(), NullEquality::NullEqualsNull) {
writeln!(f, "NullsEqual: true")?;
}
if let Some(filter) = self.filter.as_ref() {
writeln!(f, "filter={filter}")?;
}
Ok(())
}
}
}
}
impl ExecutionPlan for HashJoinExec {
fn name(&self) -> &'static str {
"HashJoinExec"
}
fn as_any(&self) -> &dyn Any {
self
}
fn properties(&self) -> &PlanProperties {
&self.cache
}
fn required_input_distribution(&self) -> Vec<Distribution> {
match self.mode {
PartitionMode::CollectLeft => vec![
Distribution::SinglePartition,
Distribution::UnspecifiedDistribution,
],
PartitionMode::Partitioned => {
let (left_expr, right_expr) = self
.on
.iter()
.map(|(l, r)| (Arc::clone(l), Arc::clone(r)))
.unzip();
vec![
Distribution::HashPartitioned(left_expr),
Distribution::HashPartitioned(right_expr),
]
}
PartitionMode::Auto => vec![
Distribution::UnspecifiedDistribution,
Distribution::UnspecifiedDistribution,
],
}
}
// For [JoinType::Inner] and [JoinType::RightSemi] in hash joins, the probe phase initiates by
// applying the hash function to convert the join key(s) in each row into a hash value from the
// probe side table in the order they're arranged. The hash value is used to look up corresponding
// entries in the hash table that was constructed from the build side table during the build phase.
//
// Because of the immediate generation of result rows once a match is found,
// the output of the join tends to follow the order in which the rows were read from
// the probe side table. This is simply due to the sequence in which the rows were processed.
// Hence, it appears that the hash join is preserving the order of the probe side.
//
// Meanwhile, in the case of a [JoinType::RightAnti] hash join,
// the unmatched rows from the probe side are also kept in order.
// This is because the **`RightAnti`** join is designed to return rows from the right
// (probe side) table that have no match in the left (build side) table. Because the rows
// are processed sequentially in the probe phase, and unmatched rows are directly output
// as results, these results tend to retain the order of the probe side table.
fn maintains_input_order(&self) -> Vec<bool> {
Self::maintains_input_order(self.join_type)
}
fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
vec![&self.left, &self.right]
}
/// Creates a new HashJoinExec with different children while preserving configuration.
///
/// This method is called during query optimization when the optimizer creates new
/// plan nodes. Importantly, it creates a fresh bounds_accumulator via `try_new`
/// rather than cloning the existing one because partitioning may have changed.
fn with_new_children(
self: Arc<Self>,
children: Vec<Arc<dyn ExecutionPlan>>,
) -> Result<Arc<dyn ExecutionPlan>> {