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

//! Hash computation and hash table lookup expressions for dynamic filtering

use std::{fmt::Display, hash::Hash, sync::Arc};

use arrow::{
    array::{ArrayRef, BooleanArray, BooleanBufferBuilder, UInt64Array},
    datatypes::{DataType, Schema},
    record_batch::RecordBatch,
};
use datafusion_common::hash_utils::RandomState;
use datafusion_common::hash_utils::{create_hashes, with_hashes};
use datafusion_common::{Result, internal_err};
use datafusion_expr::ColumnarValue;
use datafusion_expr_common::dyn_eq::DynHash;
use datafusion_physical_expr_common::physical_expr::{PhysicalExpr, PhysicalExprRef};

use crate::joins::Map;
use crate::joins::key_range_bitmap::KeyRangeBitmap;
use crate::repartition::RangeExpr;

/// RandomState wrapper that preserves the seed used to create it.
///
/// This is needed because `RandomState` doesn't expose its seed after creation,
/// but we need them for serialization (e.g., protobuf serde).
#[derive(Clone, Debug)]
pub struct SeededRandomState {
    random_state: RandomState,
    seed: u64,
}

impl SeededRandomState {
    /// Create a new SeededRandomState with the given seed.
    pub const fn with_seed(k: u64) -> Self {
        Self {
            random_state: RandomState::with_seed(k),
            seed: k,
        }
    }

    /// Get the inner RandomState.
    pub fn random_state(&self) -> &RandomState {
        &self.random_state
    }

    /// Get the seed used to create this RandomState.
    pub fn seed(&self) -> u64 {
        self.seed
    }
}

/// Physical expression that computes hash values for a set of columns
///
/// This expression computes the hash of join key columns using a specific RandomState.
/// It returns a UInt64Array containing the hash values.
///
/// This is used for:
/// - Computing routing hashes (with RepartitionExec's 0,0,0,0 seeds)
/// - Computing lookup hashes (with HashJoin's 'J','O','I','N' seeds)
pub struct HashExpr {
    /// Columns to hash
    on_columns: Vec<PhysicalExprRef>,
    /// Random state for hashing (with seeds preserved for serialization)
    random_state: SeededRandomState,
    /// Description for display
    description: String,
}

impl HashExpr {
    /// Create a new HashExpr
    ///
    /// # Arguments
    /// * `on_columns` - Columns to hash
    /// * `random_state` - SeededRandomState for hashing
    /// * `description` - Description for debugging (e.g., "hash_repartition", "hash_join")
    pub fn new(
        on_columns: Vec<PhysicalExprRef>,
        random_state: SeededRandomState,
        description: String,
    ) -> Self {
        Self {
            on_columns,
            random_state,
            description,
        }
    }

    /// Get the columns being hashed.
    pub fn on_columns(&self) -> &[PhysicalExprRef] {
        &self.on_columns
    }

    /// Get the seed used for hashing.
    pub fn seed(&self) -> u64 {
        self.random_state.seed()
    }

    /// Get the description.
    pub fn description(&self) -> &str {
        &self.description
    }
}

impl std::fmt::Debug for HashExpr {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let cols = self
            .on_columns
            .iter()
            .map(|e| e.to_string())
            .collect::<Vec<_>>()
            .join(", ");
        let seed = self.seed();
        write!(f, "{}({cols}, [{seed}])", self.description)
    }
}

impl Hash for HashExpr {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.on_columns.dyn_hash(state);
        self.description.hash(state);
        self.seed().hash(state);
    }
}

impl PartialEq for HashExpr {
    fn eq(&self, other: &Self) -> bool {
        self.on_columns == other.on_columns
            && self.description == other.description
            && self.seed() == other.seed()
    }
}

impl Eq for HashExpr {}

impl Display for HashExpr {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.description)
    }
}

impl PhysicalExpr for HashExpr {
    fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
        self.on_columns.iter().collect()
    }

    fn with_new_children(
        self: Arc<Self>,
        children: Vec<Arc<dyn PhysicalExpr>>,
    ) -> Result<Arc<dyn PhysicalExpr>> {
        Ok(Arc::new(HashExpr::new(
            children,
            self.random_state.clone(),
            self.description.clone(),
        )))
    }

    fn data_type(&self, _input_schema: &Schema) -> Result<DataType> {
        Ok(DataType::UInt64)
    }

    fn nullable(&self, _input_schema: &Schema) -> Result<bool> {
        Ok(false)
    }

    fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
        let num_rows = batch.num_rows();

        // Evaluate columns
        let keys_values = evaluate_columns(&self.on_columns, batch)?;

        // Compute hashes
        let mut hashes_buffer = vec![0; num_rows];
        create_hashes(
            &keys_values,
            self.random_state.random_state(),
            &mut hashes_buffer,
        )?;

        Ok(ColumnarValue::Array(Arc::new(UInt64Array::from(
            hashes_buffer,
        ))))
    }

    fn fmt_sql(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.description)
    }

    #[cfg(feature = "proto")]
    fn try_to_proto(
        &self,
        ctx: &datafusion_physical_expr_common::physical_expr::proto_encode::PhysicalExprEncodeCtx<'_>,
    ) -> Result<Option<datafusion_proto_models::protobuf::PhysicalExprNode>> {
        use datafusion_proto_models::protobuf;

        // Destructure exhaustively (no `..`) so that a newly added field is a
        // compile error here instead of being silently left out of the proto.
        let Self {
            on_columns,
            random_state,
            description,
        } = self;

        let on_columns = ctx.encode_children_expressions(on_columns)?;
        Ok(Some(protobuf::PhysicalExprNode {
            expr_id: None,
            expr_type: Some(protobuf::physical_expr_node::ExprType::HashExpr(
                protobuf::PhysicalHashExprNode {
                    on_columns,
                    // only the seed is serialized; `RandomState` is rebuilt
                    // from it by `SeededRandomState::with_seed` on decode
                    seed0: random_state.seed(),
                    description: description.clone(),
                },
            )),
        }))
    }
}

#[cfg(feature = "proto")]
impl HashExpr {
    /// Reconstruct a [`HashExpr`] from its protobuf representation.
    ///
    /// Takes the whole [`PhysicalExprNode`], the exact inverse of what
    /// [`PhysicalExpr::try_to_proto`] produces, so every expression's
    /// `try_from_proto` shares one signature. Child sub-expressions are
    /// decoded recursively via [`PhysicalExprDecodeCtx::decode`].
    ///
    /// [`PhysicalExprNode`]: datafusion_proto_models::protobuf::PhysicalExprNode
    /// [`PhysicalExpr::try_to_proto`]: datafusion_physical_expr_common::physical_expr::PhysicalExpr::try_to_proto
    /// [`PhysicalExprDecodeCtx::decode`]: datafusion_physical_expr_common::physical_expr::proto_decode::PhysicalExprDecodeCtx::decode
    pub fn try_from_proto(
        node: &datafusion_proto_models::protobuf::PhysicalExprNode,
        ctx: &datafusion_physical_expr_common::physical_expr::proto_decode::PhysicalExprDecodeCtx<'_>,
    ) -> Result<Arc<dyn PhysicalExpr>> {
        use datafusion_proto_models::protobuf;
        let Some(protobuf::physical_expr_node::ExprType::HashExpr(hash_expr)) =
            &node.expr_type
        else {
            return internal_err!("PhysicalExprNode is not a HashExpr");
        };
        // Destructure exhaustively (no `..`) so that a newly added proto field
        // is a compile error here instead of being silently ignored.
        let protobuf::PhysicalHashExprNode {
            on_columns,
            seed0,
            description,
        } = hash_expr;

        let on_columns = ctx.decode_children_expressions(on_columns)?;
        Ok(Arc::new(HashExpr::new(
            on_columns,
            SeededRandomState::with_seed(*seed0),
            description.clone(),
        )))
    }
}

/// Physical expression that checks join keys in a [`Map`] (hash table or array map).
///
/// Returns a [`BooleanArray`] indicating if join keys (from `on_columns`) exist in the map.
// TODO: rename to MapLookupExpr
pub struct HashTableLookupExpr {
    /// Columns in the ON clause used to compute the join key for lookups
    on_columns: Vec<PhysicalExprRef>,
    /// Random state for hashing (with seeds preserved for serialization)
    random_state: SeededRandomState,
    /// Map(s) to check against
    lookup: Lookup,
    /// Description for display
    description: String,
    /// Shared pruning-only view of the build side's key range
    pruning_bitmap: Option<Arc<KeyRangeBitmap>>,
}

/// The build side a [`HashTableLookupExpr`] checks probe keys against.
#[derive(Clone)]
enum Lookup {
    /// One map holding every build key, probed directly with no routing.
    Single(Arc<Map>),
    /// One hash table per build partition of a `Partitioned` join, `None` where
    /// the partition is empty. A key is only ever built into the partition its
    /// key routes to, so each probe row is looked up in that partition's table
    /// alone: no `CASE` over per-partition filters, and no merged table.
    Routed {
        router: PartitionRouter,
        maps: Arc<[Option<Arc<Map>>]>,
    },
}

/// Assigns probe rows to the build partition their key was repartitioned to.
///
/// # Public Only for Internal Use:
/// Public only because [`HashTableLookupExpr::new`] takes it; not part of the
/// supported public API.
#[doc(hidden)]
#[derive(Clone)]
pub enum PartitionRouter {
    /// `hash(keys) % partitions`, as hash repartitioning routes rows.
    Hash(SeededRandomState),
    /// The probe side's range partitioning.
    Range(Arc<RangeExpr>),
}

impl PartitionRouter {
    /// Writes the partition of each row of `keys` to `partition_ids`, which
    /// holds one slot per row.
    fn route(
        &self,
        keys: &[ArrayRef],
        partitions: usize,
        partition_ids: &mut Vec<u64>,
    ) -> Result<()> {
        match self {
            PartitionRouter::Hash(random_state) => {
                partition_ids.resize(keys[0].len(), 0);
                create_hashes(keys, random_state.random_state(), partition_ids)?;
                let partitions = partitions as u64;
                for id in partition_ids.iter_mut() {
                    *id %= partitions;
                }
                Ok(())
            }
            PartitionRouter::Range(range) => {
                range.route_partition_ids(keys, partition_ids)
            }
        }
    }

    fn seed(&self) -> Option<u64> {
        match self {
            PartitionRouter::Hash(random_state) => Some(random_state.seed()),
            PartitionRouter::Range(_) => None,
        }
    }
}

impl HashTableLookupExpr {
    /// Create a new HashTableLookupExpr that looks each probe row up in the
    /// map of the build partition `router` assigns it to.
    ///
    /// # Arguments
    /// * `on_columns` - Columns in the ON clause used to compute the join key
    /// * `random_state` - SeededRandomState for hashing
    /// * `router` - Routes each probe row to the partition its key was
    ///   repartitioned to; `None` when `maps` is a single map
    /// * `maps` - One entry per build partition, `None` for an empty partition
    /// * `description` - Description for debugging
    /// * `pruning_bitmap` - key-range summary covering every partition's keys
    ///   for pruning only, or `None`
    ///
    /// A single non-empty map is probed directly without routing, so it may be
    /// any [`Map`] and `router` is ignored. Otherwise `router` is required and
    /// every map must be a [`Map::HashMap`].
    ///
    /// # Public Only for Internal Use:
    /// `datafusion-proto` tests require this constructor, but it is not part of
    /// the supported public API.
    #[doc(hidden)]
    pub fn new(
        on_columns: Vec<PhysicalExprRef>,
        random_state: SeededRandomState,
        router: Option<PartitionRouter>,
        maps: Vec<Option<Arc<Map>>>,
        description: String,
        pruning_bitmap: Option<Arc<KeyRangeBitmap>>,
    ) -> Result<Self> {
        let lookup = match (router, maps.as_slice()) {
            // Every row routes to the only partition, so skip routing.
            (_, [Some(map)]) => Lookup::Single(Arc::clone(map)),
            (None, _) => {
                return internal_err!(
                    "a lookup over anything but one non-empty map needs a partition router"
                );
            }
            (Some(router), _) => {
                if maps
                    .iter()
                    .flatten()
                    .any(|map| !matches!(map.as_ref(), Map::HashMap(_)))
                {
                    return internal_err!(
                        "routed lookups only support hash table partitions"
                    );
                }
                Lookup::Routed {
                    router,
                    maps: maps.into(),
                }
            }
        };
        Ok(Self {
            on_columns,
            random_state,
            lookup,
            description,
            pruning_bitmap,
        })
    }

    /// Which parts of this build side's key range hold keys, for container pruning.
    pub fn pruning_bitmap(&self) -> Option<&Arc<KeyRangeBitmap>> {
        self.pruning_bitmap.as_ref()
    }

    /// Membership of each row of `keys` in the hash table of its routed partition.
    fn evaluate_routed(
        &self,
        keys: &[ArrayRef],
        router: &PartitionRouter,
        maps: &[Option<Arc<Map>>],
    ) -> Result<BooleanArray> {
        let num_rows = keys[0].len();
        let mut partition_ids = Vec::with_capacity(num_rows);
        router.route(keys, maps.len(), &mut partition_ids)?;

        with_hashes(keys, self.random_state.random_state(), |hashes| {
            // Counting sort of the rows by partition, so each table is probed
            // once per batch over a contiguous run of its rows' hashes.
            let mut starts = vec![0usize; maps.len() + 1];
            for &id in &partition_ids {
                starts[id as usize + 1] += 1;
            }
            for i in 0..maps.len() {
                starts[i + 1] += starts[i];
            }
            let mut next = starts.clone();
            let mut rows = vec![0u32; num_rows];
            let mut sorted_hashes = vec![0u64; num_rows];
            for (row, (&id, &hash)) in partition_ids.iter().zip(hashes).enumerate() {
                let slot = &mut next[id as usize];
                rows[*slot] = row as u32;
                sorted_hashes[*slot] = hash;
                *slot += 1;
            }

            let mut matched = BooleanBufferBuilder::new(num_rows);
            matched.append_n(num_rows, false);
            for (partition, map) in maps.iter().enumerate() {
                // An empty partition holds no key, so its rows stay unmatched.
                let Some(map) = map else { continue };
                let Map::HashMap(map) = map.as_ref() else {
                    return internal_err!(
                        "routed lookups only support hash table partitions"
                    );
                };
                let run = starts[partition]..starts[partition + 1];
                if run.is_empty() {
                    continue;
                }
                let hits = map.contain_hashes(&sorted_hashes[run.clone()]);
                for hit in hits.values().set_indices() {
                    matched.set_bit(rows[run.start + hit] as usize, true);
                }
            }
            Ok(BooleanArray::new(matched.finish(), None))
        })
    }
}
impl std::fmt::Debug for HashTableLookupExpr {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let cols = self
            .on_columns
            .iter()
            .map(|e| e.to_string())
            .collect::<Vec<_>>()
            .join(", ");
        let seed = self.random_state.seed();
        match &self.lookup {
            Lookup::Single(_) => write!(f, "{}({cols}, [{seed}])", self.description),
            Lookup::Routed { router, maps } => {
                let router = match router.seed() {
                    Some(routing_seed) => format!("hash [{routing_seed}]"),
                    None => "range".to_string(),
                };
                write!(
                    f,
                    "{}({cols}, [{seed}], routed by {router} over {} partitions)",
                    self.description,
                    maps.len()
                )
            }
        }
    }
}

impl Hash for HashTableLookupExpr {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.on_columns.dyn_hash(state);
        self.description.hash(state);
        self.random_state.seed().hash(state);
        // Hash immutable map identity, consistently with pointer equality below.
        self.lookup.identity().hash(state);
    }
}

impl PartialEq for HashTableLookupExpr {
    fn eq(&self, other: &Self) -> bool {
        // Sharing an immutable map implies equal contents, including across
        // prepared-build consumers. Distinct maps need no expensive deep comparison.
        self.on_columns == other.on_columns
            && self.description == other.description
            && self.random_state.seed() == other.random_state.seed()
            && self.lookup.identity() == other.lookup.identity()
    }
}

impl Eq for HashTableLookupExpr {}

impl Lookup {
    /// Identity of the immutable build-side maps. A routed lookup's router is
    /// created together with its maps, so the maps identify it as well.
    fn identity(&self) -> *const () {
        match self {
            Lookup::Single(map) => Arc::as_ptr(map).cast(),
            Lookup::Routed { maps, .. } => Arc::as_ptr(maps).cast(),
        }
    }
}

impl Display for HashTableLookupExpr {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.description)
    }
}

impl PhysicalExpr for HashTableLookupExpr {
    fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
        self.on_columns.iter().collect()
    }

    fn with_new_children(
        self: Arc<Self>,
        children: Vec<Arc<dyn PhysicalExpr>>,
    ) -> Result<Arc<dyn PhysicalExpr>> {
        Ok(Arc::new(HashTableLookupExpr {
            on_columns: children,
            random_state: self.random_state.clone(),
            lookup: self.lookup.clone(),
            description: self.description.clone(),
            pruning_bitmap: self.pruning_bitmap.clone(),
        }))
    }

    fn data_type(&self, _input_schema: &Schema) -> Result<DataType> {
        Ok(DataType::Boolean)
    }

    fn nullable(&self, _input_schema: &Schema) -> Result<bool> {
        Ok(false)
    }

    fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
        // Evaluate columns
        let join_keys = evaluate_columns(&self.on_columns, batch)?;

        match &self.lookup {
            Lookup::Single(map) => match map.as_ref() {
                Map::HashMap(map) => {
                    with_hashes(&join_keys, self.random_state.random_state(), |hashes| {
                        let array = map.contain_hashes(hashes);
                        Ok(ColumnarValue::Array(Arc::new(array)))
                    })
                }
                Map::ArrayMap(map) => {
                    let array = map.contain_keys(&join_keys)?;
                    Ok(ColumnarValue::Array(Arc::new(array)))
                }
            },
            Lookup::Routed { router, maps } => {
                let array = self.evaluate_routed(&join_keys, router, maps)?;
                Ok(ColumnarValue::Array(Arc::new(array)))
            }
        }
    }
    #[cfg(feature = "proto")]
    fn try_to_proto(
        &self,
        _ctx: &datafusion_physical_expr_common::physical_expr::proto_encode::PhysicalExprEncodeCtx<'_>,
    ) -> Result<Option<datafusion_proto_models::protobuf::PhysicalExprNode>> {
        use datafusion_proto_models::protobuf;
        use datafusion_proto_models::protobuf::physical_expr_node::ExprType;

        // Destructure exhaustively (no `..`) so that a newly added field is a
        // compile error here, forcing a decision about whether the lit(true)
        // replacement below is still the right thing to emit.
        let Self {
            // deliberately not serialized: the whole expression is replaced
            // with lit(true), see the comment below
            on_columns: _,
            random_state: _,
            lookup: _,
            description: _,
            pruning_bitmap: _,
        } = self;

        // HashTableLookupExpr holds a runtime Arc<Map> (the build-side hash
        // table) that cannot be serialized, so it is replaced with lit(true).
        //
        // Dynamic filtering is a performance optimisation only — replacing the
        // lookup with lit(true) preserves correctness by allowing all rows
        // through.
        //
        // If a plan is serialized before execution, HashTableLookupExpr is not
        // yet present in the dynamic filter expression.
        //
        // If a plan is serialized after execution, any runtime-created
        // HashTableLookupExpr is replaced during serialization. Re-executing
        // the plan requires reset_state(), after which HashJoinExec rebuilds
        // fresh dynamic filters at runtime.
        let value = datafusion_proto_common::ScalarValue {
            value: Some(datafusion_proto_common::scalar_value::Value::BoolValue(
                true,
            )),
        };
        Ok(Some(protobuf::PhysicalExprNode {
            expr_id: None,
            expr_type: Some(ExprType::Literal(value)),
        }))
    }
    fn fmt_sql(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.description)
    }
}

fn evaluate_columns(
    columns: &[PhysicalExprRef],
    batch: &RecordBatch,
) -> Result<Vec<ArrayRef>> {
    let num_rows = batch.num_rows();
    columns
        .iter()
        .map(|c| c.evaluate(batch)?.into_array(num_rows))
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::joins::join_hash_map::JoinHashMapU32;
    use datafusion_common::ScalarValue;
    use datafusion_physical_expr::expressions::Column;
    use std::collections::hash_map::DefaultHasher;
    use std::hash::Hasher;

    fn compute_hash<T: Hash>(value: &T) -> u64 {
        let mut hasher = DefaultHasher::new();
        value.hash(&mut hasher);
        hasher.finish()
    }

    /// The pruning bitmap must survive `with_new_children`, which a scan calls
    /// once per file.
    #[test]
    fn test_pruning_bitmap_shared_with_derived_children() -> Result<()> {
        let keys: ArrayRef = Arc::new(arrow::array::Int64Array::from(vec![0, 1_000_000]));
        let bitmap = Arc::new(
            KeyRangeBitmap::try_new(
                &keys,
                &ScalarValue::Int64(Some(0)),
                &ScalarValue::Int64(Some(1_000_000)),
                2,
            )
            .ok_or_else(|| {
                datafusion_common::internal_datafusion_err!(
                    "two keys a million apart leave prunable gaps"
                )
            })?,
        );
        let expr = Arc::new(HashTableLookupExpr::new(
            vec![Arc::new(Column::new("a", 0))],
            SeededRandomState::with_seed(1),
            None,
            vec![Some(Arc::new(Map::HashMap(Box::new(
                JoinHashMapU32::with_capacity(10),
            ))))],
            "hash_lookup".to_string(),
            Some(Arc::clone(&bitmap)),
        )?);

        let derived = expr.with_new_children(vec![Arc::new(Column::new("a", 7))])?;
        let derived = derived.downcast_ref::<HashTableLookupExpr>().unwrap();
        assert_eq!(derived.children()[0].to_string(), "a@7");
        assert!(Arc::ptr_eq(&bitmap, derived.pruning_bitmap().unwrap()));
        Ok(())
    }

    #[test]
    fn test_hash_expr_eq_same() {
        let col_a: PhysicalExprRef = Arc::new(Column::new("a", 0));
        let col_b: PhysicalExprRef = Arc::new(Column::new("b", 1));

        let expr1 = HashExpr::new(
            vec![Arc::clone(&col_a), Arc::clone(&col_b)],
            SeededRandomState::with_seed(1),
            "test_hash".to_string(),
        );

        let expr2 = HashExpr::new(
            vec![Arc::clone(&col_a), Arc::clone(&col_b)],
            SeededRandomState::with_seed(1),
            "test_hash".to_string(),
        );

        assert_eq!(expr1, expr2);
    }

    #[test]
    fn test_hash_expr_eq_different_columns() {
        let col_a: PhysicalExprRef = Arc::new(Column::new("a", 0));
        let col_b: PhysicalExprRef = Arc::new(Column::new("b", 1));
        let col_c: PhysicalExprRef = Arc::new(Column::new("c", 2));

        let expr1 = HashExpr::new(
            vec![Arc::clone(&col_a), Arc::clone(&col_b)],
            SeededRandomState::with_seed(1),
            "test_hash".to_string(),
        );

        let expr2 = HashExpr::new(
            vec![Arc::clone(&col_a), Arc::clone(&col_c)],
            SeededRandomState::with_seed(1),
            "test_hash".to_string(),
        );

        assert_ne!(expr1, expr2);
    }

    #[test]
    fn test_hash_expr_eq_different_description() {
        let col_a: PhysicalExprRef = Arc::new(Column::new("a", 0));

        let expr1 = HashExpr::new(
            vec![Arc::clone(&col_a)],
            SeededRandomState::with_seed(1),
            "hash_one".to_string(),
        );

        let expr2 = HashExpr::new(
            vec![Arc::clone(&col_a)],
            SeededRandomState::with_seed(1),
            "hash_two".to_string(),
        );

        assert_ne!(expr1, expr2);
    }

    #[test]
    fn test_hash_expr_eq_different_seeds() {
        let col_a: PhysicalExprRef = Arc::new(Column::new("a", 0));

        let expr1 = HashExpr::new(
            vec![Arc::clone(&col_a)],
            SeededRandomState::with_seed(1),
            "test_hash".to_string(),
        );

        let expr2 = HashExpr::new(
            vec![Arc::clone(&col_a)],
            SeededRandomState::with_seed(5),
            "test_hash".to_string(),
        );

        assert_ne!(expr1, expr2);
    }

    #[test]
    fn test_hash_expr_hash_consistency() {
        let col_a: PhysicalExprRef = Arc::new(Column::new("a", 0));
        let col_b: PhysicalExprRef = Arc::new(Column::new("b", 1));

        let expr1 = HashExpr::new(
            vec![Arc::clone(&col_a), Arc::clone(&col_b)],
            SeededRandomState::with_seed(1),
            "test_hash".to_string(),
        );

        let expr2 = HashExpr::new(
            vec![Arc::clone(&col_a), Arc::clone(&col_b)],
            SeededRandomState::with_seed(1),
            "test_hash".to_string(),
        );

        // Equal expressions should have equal hashes
        assert_eq!(expr1, expr2);
        assert_eq!(compute_hash(&expr1), compute_hash(&expr2));
    }

    #[cfg(feature = "proto")]
    mod proto_tests {
        use super::*;
        use arrow::datatypes::{DataType, Field};
        use datafusion_common::internal_datafusion_err;
        use datafusion_physical_expr_common::physical_expr::proto_decode::{
            PhysicalExprDecode, PhysicalExprDecodeCtx,
        };
        use datafusion_physical_expr_common::physical_expr::proto_encode::{
            PhysicalExprEncode, PhysicalExprEncodeCtx,
        };
        use datafusion_proto_models::protobuf;

        struct TestEncoder;

        impl PhysicalExprEncode for TestEncoder {
            fn encode(
                &self,
                expr: &Arc<dyn PhysicalExpr>,
            ) -> Result<protobuf::PhysicalExprNode> {
                let ctx = PhysicalExprEncodeCtx::new(self);
                expr.try_to_proto(&ctx)?.ok_or_else(|| {
                    internal_datafusion_err!("test encoder cannot encode {expr:?}")
                })
            }
        }

        struct TestDecoder;

        impl PhysicalExprDecode for TestDecoder {
            fn decode(
                &self,
                node: &protobuf::PhysicalExprNode,
                schema: &Schema,
            ) -> Result<Arc<dyn PhysicalExpr>> {
                let ctx = PhysicalExprDecodeCtx::new(schema, self);
                match &node.expr_type {
                    Some(protobuf::physical_expr_node::ExprType::Column(_)) => {
                        Column::try_from_proto(node, &ctx)
                    }
                    _ => internal_err!("test decoder cannot decode {node:?}"),
                }
            }
        }

        fn test_decode_ctx<'a>(
            schema: &'a Schema,
            decoder: &'a TestDecoder,
        ) -> PhysicalExprDecodeCtx<'a> {
            PhysicalExprDecodeCtx::new(schema, decoder)
        }

        #[test]
        fn hash_expr_try_to_proto() {
            let expr = HashExpr::new(
                vec![Arc::new(Column::new("a", 0)), Arc::new(Column::new("b", 1))],
                SeededRandomState::with_seed(42),
                "hash_join".to_string(),
            );
            let encoder = TestEncoder;
            let ctx = PhysicalExprEncodeCtx::new(&encoder);

            let proto = expr.try_to_proto(&ctx).unwrap().unwrap();

            assert_eq!(proto.expr_id, None);
            let hash_expr = match proto.expr_type.unwrap() {
                protobuf::physical_expr_node::ExprType::HashExpr(hash_expr) => hash_expr,
                other => panic!("expected HashExpr, got {other:?}"),
            };
            assert_eq!(hash_expr.seed0, 42);
            assert_eq!(hash_expr.description, "hash_join");
            assert_eq!(hash_expr.on_columns.len(), 2);
            assert!(
                hash_expr
                    .on_columns
                    .iter()
                    .all(|expr| expr.expr_id.is_none())
            );
        }

        #[test]
        fn hash_expr_try_from_proto() {
            let schema = Schema::new(vec![
                Field::new("a", DataType::Int32, false),
                Field::new("b", DataType::Utf8, true),
            ]);
            let decoder = TestDecoder;
            let ctx = test_decode_ctx(&schema, &decoder);
            let proto = protobuf::PhysicalExprNode {
                expr_id: None,
                expr_type: Some(protobuf::physical_expr_node::ExprType::HashExpr(
                    protobuf::PhysicalHashExprNode {
                        on_columns: vec![
                            protobuf::PhysicalExprNode {
                                expr_id: None,
                                expr_type: Some(
                                    protobuf::physical_expr_node::ExprType::Column(
                                        protobuf::PhysicalColumn {
                                            name: "a".to_string(),
                                            index: 0,
                                        },
                                    ),
                                ),
                            },
                            protobuf::PhysicalExprNode {
                                expr_id: None,
                                expr_type: Some(
                                    protobuf::physical_expr_node::ExprType::Column(
                                        protobuf::PhysicalColumn {
                                            name: "b".to_string(),
                                            index: 1,
                                        },
                                    ),
                                ),
                            },
                        ],
                        seed0: 42,
                        description: "hash_join".to_string(),
                    },
                )),
            };

            let expr = HashExpr::try_from_proto(&proto, &ctx).unwrap();
            let expr = expr.downcast_ref::<HashExpr>().unwrap();

            assert_eq!(expr.seed(), 42);
            assert_eq!(expr.description(), "hash_join");
            assert_eq!(expr.on_columns().len(), 2);
            assert_eq!(
                expr.on_columns()[0]
                    .downcast_ref::<Column>()
                    .map(|col| (col.name(), col.index())),
                Some(("a", 0))
            );
            assert_eq!(
                expr.on_columns()[1]
                    .downcast_ref::<Column>()
                    .map(|col| (col.name(), col.index())),
                Some(("b", 1))
            );
        }

        #[test]
        fn hash_expr_try_from_proto_rejects_wrong_node_type() {
            let schema = Schema::empty();
            let decoder = TestDecoder;
            let ctx = test_decode_ctx(&schema, &decoder);
            let proto = protobuf::PhysicalExprNode {
                expr_id: None,
                expr_type: Some(protobuf::physical_expr_node::ExprType::Column(
                    protobuf::PhysicalColumn {
                        name: "a".to_string(),
                        index: 0,
                    },
                )),
            };

            let err = HashExpr::try_from_proto(&proto, &ctx).unwrap_err();
            assert!(
                err.to_string()
                    .contains("PhysicalExprNode is not a HashExpr"),
                "{err}"
            );
        }
    }

    #[test]
    fn test_hash_table_lookup_expr_eq_same() -> Result<()> {
        let col_a: PhysicalExprRef = Arc::new(Column::new("a", 0));
        let hash_map =
            Arc::new(Map::HashMap(Box::new(JoinHashMapU32::with_capacity(10))));

        let expr1 = HashTableLookupExpr::new(
            vec![Arc::clone(&col_a)],
            SeededRandomState::with_seed(1),
            None,
            vec![Some(Arc::clone(&hash_map))],
            "lookup".to_string(),
            None,
        )?;

        let expr2 = HashTableLookupExpr::new(
            vec![Arc::clone(&col_a)],
            SeededRandomState::with_seed(1),
            None,
            vec![Some(Arc::clone(&hash_map))],
            "lookup".to_string(),
            None,
        )?;

        assert_eq!(expr1, expr2);
        Ok(())
    }

    #[test]
    fn test_hash_table_lookup_expr_eq_different_columns() -> Result<()> {
        let col_a: PhysicalExprRef = Arc::new(Column::new("a", 0));
        let col_b: PhysicalExprRef = Arc::new(Column::new("b", 1));

        let hash_map =
            Arc::new(Map::HashMap(Box::new(JoinHashMapU32::with_capacity(10))));

        let expr1 = HashTableLookupExpr::new(
            vec![Arc::clone(&col_a)],
            SeededRandomState::with_seed(1),
            None,
            vec![Some(Arc::clone(&hash_map))],
            "lookup".to_string(),
            None,
        )?;

        let expr2 = HashTableLookupExpr::new(
            vec![Arc::clone(&col_b)],
            SeededRandomState::with_seed(1),
            None,
            vec![Some(Arc::clone(&hash_map))],
            "lookup".to_string(),
            None,
        )?;

        assert_ne!(expr1, expr2);
        Ok(())
    }

    #[test]
    fn test_hash_table_lookup_expr_eq_different_description() -> Result<()> {
        let col_a: PhysicalExprRef = Arc::new(Column::new("a", 0));
        let hash_map =
            Arc::new(Map::HashMap(Box::new(JoinHashMapU32::with_capacity(10))));

        let expr1 = HashTableLookupExpr::new(
            vec![Arc::clone(&col_a)],
            SeededRandomState::with_seed(1),
            None,
            vec![Some(Arc::clone(&hash_map))],
            "lookup_one".to_string(),
            None,
        )?;

        let expr2 = HashTableLookupExpr::new(
            vec![Arc::clone(&col_a)],
            SeededRandomState::with_seed(1),
            None,
            vec![Some(Arc::clone(&hash_map))],
            "lookup_two".to_string(),
            None,
        )?;

        assert_ne!(expr1, expr2);
        Ok(())
    }

    #[test]
    fn test_hash_table_lookup_expr_eq_different_hash_map() -> Result<()> {
        let col_a: PhysicalExprRef = Arc::new(Column::new("a", 0));

        // Two different Arc pointers (even with same content) should not be equal
        let hash_map1 =
            Arc::new(Map::HashMap(Box::new(JoinHashMapU32::with_capacity(10))));
        let hash_map2 =
            Arc::new(Map::HashMap(Box::new(JoinHashMapU32::with_capacity(10))));
        let expr1 = HashTableLookupExpr::new(
            vec![Arc::clone(&col_a)],
            SeededRandomState::with_seed(1),
            None,
            vec![Some(hash_map1)],
            "lookup".to_string(),
            None,
        )?;

        let expr2 = HashTableLookupExpr::new(
            vec![Arc::clone(&col_a)],
            SeededRandomState::with_seed(1),
            None,
            vec![Some(hash_map2)],
            "lookup".to_string(),
            None,
        )?;

        // Different Arc pointers means not equal (uses Arc::ptr_eq)
        assert_ne!(expr1, expr2);
        Ok(())
    }

    #[test]
    fn test_hash_table_lookup_expr_hash_consistency() -> Result<()> {
        let col_a: PhysicalExprRef = Arc::new(Column::new("a", 0));
        let hash_map =
            Arc::new(Map::HashMap(Box::new(JoinHashMapU32::with_capacity(10))));

        let expr1 = HashTableLookupExpr::new(
            vec![Arc::clone(&col_a)],
            SeededRandomState::with_seed(1),
            None,
            vec![Some(Arc::clone(&hash_map))],
            "lookup".to_string(),
            None,
        )?;

        let expr2 = HashTableLookupExpr::new(
            vec![Arc::clone(&col_a)],
            SeededRandomState::with_seed(1),
            None,
            vec![Some(Arc::clone(&hash_map))],
            "lookup".to_string(),
            None,
        )?;

        // Equal expressions should have equal hashes
        assert_eq!(expr1, expr2);
        assert_eq!(compute_hash(&expr1), compute_hash(&expr2));
        Ok(())
    }

    /// Probes `probe` against `expr`, one row per key of column `a`.
    fn lookup(expr: &HashTableLookupExpr, probe: &ArrayRef) -> Result<BooleanArray> {
        let schema = Arc::new(Schema::new(vec![arrow::datatypes::Field::new(
            "a",
            DataType::Int32,
            true,
        )]));
        let batch = RecordBatch::try_new(schema, vec![Arc::clone(probe)])?;
        let matched = expr.evaluate(&batch)?.into_array(batch.num_rows())?;
        Ok(arrow::array::AsArray::as_boolean(&matched).clone())
    }

    /// A hash table of `keys`, hashed with `random_state` as the build side
    /// hashes them.
    fn hash_table(keys: &ArrayRef, random_state: &SeededRandomState) -> Result<Arc<Map>> {
        use crate::joins::join_hash_map::JoinHashMapType;
        let mut hashes = vec![0; keys.len()];
        create_hashes([keys], random_state.random_state(), &mut hashes)?;
        let mut map = JoinHashMapU32::with_capacity(keys.len());
        map.update_from_iter(Box::new(hashes.iter().enumerate()), 0);
        Ok(Arc::new(Map::HashMap(Box::new(map))))
    }

    /// One randomly generated scenario, see [`routed_lookup_fuzz`].
    fn run_routed_lookup_scenario(seed: u64) -> Result<()> {
        use crate::repartition::{BatchPartitioner, REPARTITION_RANDOM_STATE};
        use rand::rngs::StdRng;
        use rand::{Rng, SeedableRng};

        let mut rng = StdRng::seed_from_u64(seed);
        let num_partitions = rng.random_range(1..8usize);
        // A key domain near the row counts, so probes both hit and miss.
        let build: Vec<i32> = (0..rng.random_range(0..128))
            .map(|_| rng.random_range(-64..64))
            .collect();
        let probe: Vec<Option<i32>> = (0..rng.random_range(0..128))
            .map(|_| rng.random_bool(0.9).then(|| rng.random_range(-80..80)))
            .collect();
        let context = format!(
            "seed {seed}: {num_partitions} partitions, {} build rows, {} probe rows",
            build.len(),
            probe.len()
        );

        let column: PhysicalExprRef = Arc::new(Column::new("a", 0));
        let schema = Arc::new(Schema::new(vec![arrow::datatypes::Field::new(
            "a",
            DataType::Int32,
            false,
        )]));
        let build: ArrayRef = Arc::new(arrow::array::Int32Array::from(build));
        let probe: ArrayRef = Arc::new(arrow::array::Int32Array::from(probe));
        let random_state = SeededRandomState::with_seed(1);

        // Split the build side exactly as hash repartitioning does.
        let mut maps = vec![None; num_partitions];
        BatchPartitioner::new_hash_partitioner(
            vec![Arc::clone(&column)],
            num_partitions,
            crate::metrics::Time::new(),
        )?
        .partition(
            RecordBatch::try_new(schema, vec![Arc::clone(&build)])?,
            |partition, batch| {
                maps[partition] = Some(hash_table(batch.column(0), &random_state)?);
                Ok(())
            },
        )?;
        let routed = HashTableLookupExpr::new(
            vec![Arc::clone(&column)],
            random_state.clone(),
            Some(PartitionRouter::Hash(REPARTITION_RANDOM_STATE)),
            maps,
            "routed".to_string(),
            None,
        )?;
        // Reference: the single-table lookup over the whole build side.
        let single = HashTableLookupExpr::new(
            vec![column],
            random_state.clone(),
            None,
            vec![Some(hash_table(&build, &random_state)?)],
            "single".to_string(),
            None,
        )?;

        assert_eq!(
            lookup(&routed, &probe)?,
            lookup(&single, &probe)?,
            "{context}"
        );
        Ok(())
    }

    /// Routing each probe row to its build partition's table matches one table
    /// over the whole build side, when the build side is split the way hash
    /// repartitioning splits it.
    ///
    /// `DATAFUSION_ROUTED_LOOKUP_FUZZ_ITERATIONS` and
    /// `DATAFUSION_ROUTED_LOOKUP_FUZZ_SEED` select how many scenarios run and
    /// from which seed; a failure names its seed so it can be replayed.
    #[test]
    fn routed_lookup_fuzz() -> Result<()> {
        let env_u64 = |name: &str, default: u64| {
            std::env::var(name)
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(default)
        };
        let first_seed = env_u64("DATAFUSION_ROUTED_LOOKUP_FUZZ_SEED", 0);
        let iterations = env_u64("DATAFUSION_ROUTED_LOOKUP_FUZZ_ITERATIONS", 256);
        // `saturating_add` so a replay seed near `u64::MAX` cannot overflow.
        for seed in first_seed..first_seed.saturating_add(iterations) {
            run_routed_lookup_scenario(seed)?;
        }
        Ok(())
    }
}