-
Notifications
You must be signed in to change notification settings - Fork 412
/
Join.cpp
2356 lines (2145 loc) · 88.4 KB
/
Join.cpp
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
// Copyright 2023 PingCAP, Inc.
//
// Licensed 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.
#include <Columns/ColumnUtils.h>
#include <Columns/ColumnsCommon.h>
#include <Common/ColumnsHashing.h>
#include <Common/FailPoint.h>
#include <Common/typeid_cast.h>
#include <Core/AutoSpillTrigger.h>
#include <Core/ColumnNumbers.h>
#include <DataStreams/ScanHashMapAfterProbeBlockInputStream.h>
#include <DataStreams/materializeBlock.h>
#include <DataTypes/DataTypeNullable.h>
#include <DataTypes/DataTypesNumber.h>
#include <Functions/FunctionHelpers.h>
#include <Interpreters/CrossJoinProbeHelper.h>
#include <Interpreters/Join.h>
#include <Interpreters/NullAwareSemiJoinHelper.h>
#include <Interpreters/NullableUtils.h>
#include <common/logger_useful.h>
#include <exception>
#include <magic_enum.hpp>
namespace DB
{
namespace FailPoints
{
extern const char random_join_prob_failpoint[];
extern const char exception_mpp_hash_build[];
extern const char exception_mpp_hash_probe[];
} // namespace FailPoints
namespace ErrorCodes
{
extern const int LOGICAL_ERROR;
extern const int TYPE_MISMATCH;
} // namespace ErrorCodes
namespace
{
ColumnRawPtrs getKeyColumns(const Names & key_names, const Block & block)
{
size_t keys_size = key_names.size();
ColumnRawPtrs key_columns(keys_size);
for (size_t i = 0; i < keys_size; ++i)
{
key_columns[i] = block.getByName(key_names[i]).column.get();
/// We will join only keys, where all components are not NULL.
if (key_columns[i]->isColumnNullable())
key_columns[i] = &static_cast<const ColumnNullable &>(*key_columns[i]).getNestedColumn();
}
return key_columns;
}
size_t getRestoreJoinBuildConcurrency(
size_t total_partitions,
size_t spilled_partitions,
Int64 join_restore_concurrency,
size_t total_concurrency)
{
if (join_restore_concurrency < 0)
{
/// restore serially, so one restore join will take up all the concurrency
return total_concurrency;
}
else if (join_restore_concurrency > 0)
{
/// try to restore `join_restore_concurrency` partition at a time, but restore_join_build_concurrency should be at least 2
return std::max(2, total_concurrency / join_restore_concurrency);
}
else
{
assert(total_partitions >= spilled_partitions);
size_t unspilled_partitions = total_partitions - spilled_partitions;
/// try to restore at most (unspilled_partitions - 1) partitions at a time
size_t max_concurrent_restore_partition = unspilled_partitions <= 1 ? 1 : unspilled_partitions - 1;
size_t restore_times
= (spilled_partitions + max_concurrent_restore_partition - 1) / max_concurrent_restore_partition;
size_t restore_build_concurrency = (restore_times * total_concurrency) / spilled_partitions;
return std::max(2, restore_build_concurrency);
}
}
std::pair<const ColumnUInt8::Container *, const ColumnUInt8::Container *> getDataAndNullMapVectorFromFilterColumn(
ColumnPtr & filter_column)
{
if (filter_column->isColumnConst())
filter_column = filter_column->convertToFullColumnIfConst();
if (filter_column->isColumnNullable())
{
const auto * nullable_column = checkAndGetColumn<ColumnNullable>(filter_column.get());
const auto & data_column = nullable_column->getNestedColumnPtr();
return {&checkAndGetColumn<ColumnUInt8>(data_column.get())->getData(), &nullable_column->getNullMapData()};
}
else
{
return {&checkAndGetColumn<ColumnUInt8>(filter_column.get())->getData(), nullptr};
}
}
} // namespace
using PointerHelper = PointerTypeColumnHelper<sizeof(void *)>;
const std::string Join::match_helper_prefix = "__left-semi-join-match-helper";
const DataTypePtr Join::match_helper_type = makeNullable(std::make_shared<DataTypeInt8>());
const String Join::flag_mapped_entry_helper_prefix = "__flag-mapped-entry-match-helper";
const DataTypePtr Join::flag_mapped_entry_helper_type = std::make_shared<PointerHelper::DataType>();
#ifdef DBMS_PUBLIC_GTEST
const size_t MAX_RESTORE_ROUND_IN_GTEST = 2;
#endif
Join::Join(
const Names & key_names_left_,
const Names & key_names_right_,
ASTTableJoin::Kind kind_,
ASTTableJoin::Strictness strictness_,
const String & req_id,
bool enable_fine_grained_shuffle_,
size_t fine_grained_shuffle_count_,
size_t max_bytes_before_external_join,
const SpillConfig & build_spill_config,
const SpillConfig & probe_spill_config,
Int64 join_restore_concurrency_,
const Names & tidb_output_column_names_,
const RegisterOperatorSpillContext & register_operator_spill_context_,
AutoSpillTrigger * auto_spill_trigger_,
const TiDB::TiDBCollators & collators_,
const JoinNonEqualConditions & non_equal_conditions_,
size_t max_block_size_,
size_t shallow_copy_cross_probe_threshold_,
const String & match_helper_name_,
const String & flag_mapped_entry_helper_name_,
size_t restore_round_,
size_t restore_part,
bool is_test_,
const std::vector<RuntimeFilterPtr> & runtime_filter_list_)
: restore_round(restore_round_)
, match_helper_name(match_helper_name_)
, flag_mapped_entry_helper_name(flag_mapped_entry_helper_name_)
, kind(kind_)
, strictness(strictness_)
, original_strictness(strictness)
, join_req_id(req_id)
, may_probe_side_expanded_after_join(mayProbeSideExpandedAfterJoin(kind, strictness))
, key_names_left(key_names_left_)
, key_names_right(key_names_right_)
, build_concurrency(0)
, active_build_threads(0)
, probe_concurrency(0)
, active_probe_threads(0)
, collators(collators_)
, non_equal_conditions(non_equal_conditions_)
, max_block_size(max_block_size_)
, runtime_filter_list(runtime_filter_list_)
, join_restore_concurrency(join_restore_concurrency_)
, register_operator_spill_context(register_operator_spill_context_)
, auto_spill_trigger(auto_spill_trigger_)
, shallow_copy_cross_probe_threshold(
shallow_copy_cross_probe_threshold_ > 0 ? shallow_copy_cross_probe_threshold_
: std::max(1, max_block_size / 10))
, tidb_output_column_names(tidb_output_column_names_)
, is_test(is_test_)
, log(Logger::get(
restore_round == 0 ? join_req_id
: fmt::format("{}_round_{}_part_{}", join_req_id, restore_round, restore_part)))
, enable_fine_grained_shuffle(enable_fine_grained_shuffle_)
, fine_grained_shuffle_count(fine_grained_shuffle_count_)
{
if (non_equal_conditions.other_cond_expr != nullptr)
{
/// if there is other_condition, then should keep all the valid rows during probe stage
if (strictness == ASTTableJoin::Strictness::Any)
{
strictness = ASTTableJoin::Strictness::All;
}
has_other_condition = true;
}
else
{
has_other_condition = false;
}
if (unlikely(kind == ASTTableJoin::Kind::Cross_RightOuter))
throw Exception("Cross right outer join should be converted to cross Left outer join during compile");
RUNTIME_CHECK(!(isNecessaryKindToUseRowFlaggedHashMap(kind) && strictness == ASTTableJoin::Strictness::Any));
String err = non_equal_conditions.validate(kind);
if (unlikely(!err.empty()))
throw Exception("Validate join conditions error: {}" + err);
hash_join_spill_context = std::make_shared<HashJoinSpillContext>(
build_spill_config,
probe_spill_config,
max_bytes_before_external_join,
log);
size_t max_restore_round = 4;
#ifdef DBMS_PUBLIC_GTEST
max_restore_round = MAX_RESTORE_ROUND_IN_GTEST;
#endif
if (hash_join_spill_context->supportSpill() && restore_round >= max_restore_round)
{
LOG_WARNING(log, fmt::format("restore round reach to {}, spilling will be disabled.", max_restore_round));
hash_join_spill_context->disableSpill();
}
LOG_DEBUG(
log,
"FineGrainedShuffle flag {}, stream count {}",
enable_fine_grained_shuffle,
fine_grained_shuffle_count);
}
void Join::meetError(const String & error_message_)
{
std::unique_lock lock(build_probe_mutex);
meetErrorImpl(error_message_, lock);
}
void Join::meetErrorImpl(const String & error_message_, std::unique_lock<std::mutex> &)
{
if (meet_error)
return;
meet_error = true;
error_message = error_message_.empty() ? "Join meet error" : error_message_;
build_cv.notify_all();
probe_cv.notify_all();
}
size_t Join::getTotalRowCount() const
{
std::shared_lock rw_lock(rwlock);
size_t res = 0;
if (join_map_method == JoinMapMethod::CROSS)
{
res = total_input_build_rows;
}
else
{
for (const auto & partition : partitions)
{
auto partition_lock = partition->lockPartition();
res += partition->getRowCount();
}
}
return res;
}
size_t Join::getTotalHashTableAndPoolByteCount()
{
if (join_map_method == JoinMapMethod::CROSS)
return 0;
size_t res = 0;
for (const auto & partition : partitions)
res += partition->getHashMapAndPoolMemoryUsage();
return res;
}
size_t Join::getTotalByteCount()
{
size_t res = 0;
if (isEnableSpill())
{
for (const auto & join_partition : partitions)
res += join_partition->getMemoryUsage();
}
else
{
if (join_map_method == JoinMapMethod::CROSS)
{
for (const auto & block : blocks)
res += block.bytes();
}
else
{
for (const auto & block : original_blocks)
res += block.bytes();
for (const auto & partition : partitions)
{
/// note the return value might not be accurate since it does not use lock, but should be enough for current usage
res += partition->getHashMapAndPoolByteCount();
}
}
}
if (peak_build_bytes_usage)
peak_build_bytes_usage = res;
return res;
}
size_t Join::getPeakBuildBytesUsage()
{
/// call `getTotalByteCount` first to make sure peak_build_bytes_usage has a meaningful value
getTotalByteCount();
return peak_build_bytes_usage;
}
void Join::setBuildConcurrencyAndInitJoinPartition(size_t build_concurrency_)
{
if (unlikely(build_concurrency > 0))
throw Exception(
"Logical error: `setBuildConcurrencyAndInitJoinPartition` shouldn't be called more than once",
ErrorCodes::LOGICAL_ERROR);
/// do not set active_build_threads because in compile stage, `joinBlock` will be called to get generate header, if active_build_threads
/// is set here, `joinBlock` will hang when used to get header
build_concurrency = std::max(1, build_concurrency_);
partitions.reserve(build_concurrency);
for (size_t i = 0; i < getBuildConcurrency(); ++i)
{
partitions.push_back(std::make_unique<JoinPartition>(
join_map_method,
kind,
strictness,
i,
max_block_size,
hash_join_spill_context,
log,
has_other_condition));
}
}
void Join::setSampleBlock(const Block & block)
{
sample_block_with_columns_to_add = materializeBlock(block);
/// Move from `sample_block_with_columns_to_add` key columns to `sample_block_with_keys`, keeping the order.
size_t pos = 0;
while (pos < sample_block_with_columns_to_add.columns())
{
const auto & name = sample_block_with_columns_to_add.getByPosition(pos).name;
if (key_names_right.end() != std::find(key_names_right.begin(), key_names_right.end(), name))
{
sample_block_with_keys.insert(sample_block_with_columns_to_add.getByPosition(pos));
sample_block_with_columns_to_add.erase(pos);
}
else
++pos;
}
size_t num_columns_to_add = sample_block_with_columns_to_add.columns();
for (size_t i = 0; i < num_columns_to_add; ++i)
{
auto & column = sample_block_with_columns_to_add.getByPosition(i);
if (!column.column)
column.column = column.type->createColumn();
}
/// In case of LEFT and FULL joins, if use_nulls, convert joined columns to Nullable.
if (isLeftOuterJoin(kind) || kind == ASTTableJoin::Kind::Full)
for (size_t i = 0; i < num_columns_to_add; ++i)
convertColumnToNullable(sample_block_with_columns_to_add.getByPosition(i));
if (isLeftOuterSemiFamily(kind))
sample_block_with_columns_to_add.insert(ColumnWithTypeAndName(Join::match_helper_type, match_helper_name));
}
std::shared_ptr<Join> Join::createRestoreJoin(size_t max_bytes_before_external_join_, size_t restore_partition_id)
{
return std::make_shared<Join>(
key_names_left,
key_names_right,
kind,
original_strictness,
join_req_id,
false,
0,
max_bytes_before_external_join_,
hash_join_spill_context->createBuildSpillConfig(fmt::format("{}_{}_build", join_req_id, restore_round + 1)),
hash_join_spill_context->createProbeSpillConfig(fmt::format("{}_{}_probe", join_req_id, restore_round + 1)),
join_restore_concurrency,
tidb_output_column_names,
register_operator_spill_context,
auto_spill_trigger,
collators,
non_equal_conditions,
max_block_size,
shallow_copy_cross_probe_threshold,
match_helper_name,
flag_mapped_entry_helper_name,
restore_round + 1,
restore_partition_id,
is_test);
}
void Join::initBuild(const Block & sample_block, size_t build_concurrency_)
{
std::unique_lock lock(rwlock);
if (unlikely(initialized))
throw Exception("Logical error: Join has been initialized", ErrorCodes::LOGICAL_ERROR);
initialized = true;
join_map_method = chooseJoinMapMethod(getKeyColumns(key_names_right, sample_block), key_sizes, collators);
build_sample_block = sample_block;
setBuildConcurrencyAndInitJoinPartition(build_concurrency_);
hash_join_spill_context->init(build_concurrency);
if (hash_join_spill_context->supportSpill())
{
if (join_map_method == JoinMapMethod::CROSS)
{
/// todo support spill for cross join
hash_join_spill_context->disableSpill();
LOG_WARNING(log, "Join does not support spill, reason: cross join spill is not supported");
}
if (isNullAwareSemiFamily(kind))
{
hash_join_spill_context->disableSpill();
LOG_WARNING(log, "Join does not support spill, reason: null aware join spill is not supported");
}
}
if (register_operator_spill_context != nullptr)
register_operator_spill_context(hash_join_spill_context);
if (hash_join_spill_context->isSpillEnabled())
{
hash_join_spill_context->buildBuildSpiller(build_sample_block);
}
for (auto & partition : partitions)
partition->setResizeCallbackIfNeeded();
setSampleBlock(sample_block);
build_side_marked_spilled_data.resize(build_concurrency);
}
void Join::initProbe(const Block & sample_block, size_t probe_concurrency_)
{
std::unique_lock lock(rwlock);
setProbeConcurrency(probe_concurrency_);
probe_sample_block = sample_block;
if (hash_join_spill_context->isSpillEnabled())
hash_join_spill_context->buildProbeSpiller(probe_sample_block);
probe_side_marked_spilled_data.resize(probe_concurrency);
}
Join::MarkedSpillData & Join::getBuildSideMarkedSpillData(size_t stream_index)
{
assert(stream_index < build_side_marked_spilled_data.size());
return build_side_marked_spilled_data[stream_index];
}
const Join::MarkedSpillData & Join::getBuildSideMarkedSpillData(size_t stream_index) const
{
assert(stream_index < build_side_marked_spilled_data.size());
return build_side_marked_spilled_data[stream_index];
}
bool Join::hasBuildSideMarkedSpillData(size_t stream_index) const
{
std::shared_lock lock(rwlock);
return !getBuildSideMarkedSpillData(stream_index).empty();
}
void Join::flushBuildSideMarkedSpillData(size_t stream_index)
{
std::shared_lock lock(rwlock);
auto & data = getBuildSideMarkedSpillData(stream_index);
assert(!data.empty());
for (auto & [part_id, blocks_to_spill] : data)
spillBuildSideBlocks(part_id, std::move(blocks_to_spill));
data.clear();
}
Join::MarkedSpillData & Join::getProbeSideMarkedSpillData(size_t stream_index)
{
assert(stream_index < probe_side_marked_spilled_data.size());
return probe_side_marked_spilled_data[stream_index];
}
const Join::MarkedSpillData & Join::getProbeSideMarkedSpillData(size_t stream_index) const
{
assert(stream_index < probe_side_marked_spilled_data.size());
return probe_side_marked_spilled_data[stream_index];
}
bool Join::hasProbeSideMarkedSpillData(size_t stream_index) const
{
std::shared_lock lock(rwlock);
return !getProbeSideMarkedSpillData(stream_index).empty();
}
void Join::flushProbeSideMarkedSpillData(size_t stream_index)
{
std::shared_lock lock(rwlock);
auto & data = getProbeSideMarkedSpillData(stream_index);
assert(!data.empty());
for (auto & [part_id, blocks_to_spill] : data)
spillProbeSideBlocks(part_id, std::move(blocks_to_spill));
data.clear();
}
void Join::checkAndMarkPartitionSpilledIfNeeded(size_t stream_index)
{
/// todo need to check more partitions if partition_size is not equal to total stream size
size_t partition_index = stream_index;
const auto & join_partition = partitions[partition_index];
auto partition_lock = join_partition->tryLockPartition();
if (partition_lock)
checkAndMarkPartitionSpilledIfNeededInternal(*join_partition, partition_lock, partition_index, stream_index);
/// if someone already hold the lock, it will check the spill
}
void Join::checkAndMarkPartitionSpilledIfNeededInternal(
JoinPartition & join_partition,
std::unique_lock<std::mutex> & partition_lock,
size_t partition_index,
size_t stream_index)
{
auto ret
= hash_join_spill_context->updatePartitionRevocableMemory(partition_index, join_partition.revocableBytes());
if (ret)
{
if (!hash_join_spill_context->isPartitionSpilled(partition_index))
{
/// first spill
hash_join_spill_context->markPartitionSpilled(partition_index);
join_partition.releasePartitionPoolAndHashMap(partition_lock);
}
auto blocks_to_spill = join_partition.trySpillBuildPartition(partition_lock);
markBuildSideSpillData(partition_index, std::move(blocks_to_spill), stream_index);
}
}
/// the block should be valid.
void Join::insertFromBlock(const Block & block, size_t stream_index)
{
if unlikely (block.rows() == 0)
return;
std::shared_lock lock(rwlock);
assert(stream_index < getBuildConcurrency());
total_input_build_rows += block.rows();
if (unlikely(!initialized))
throw Exception("Logical error: Join was not initialized", ErrorCodes::LOGICAL_ERROR);
if (!isEnableSpill())
{
Block * stored_block = nullptr;
{
std::lock_guard lk(blocks_lock);
blocks.push_back(block);
stored_block = &blocks.back();
original_blocks.push_back(block);
}
insertFromBlockInternal(stored_block, stream_index);
}
else
{
Blocks dispatch_blocks;
size_t block_size_to_be_inserted = build_concurrency;
if (enable_fine_grained_shuffle)
{
/// fine grain shuffle does not need dispatch
dispatch_blocks.resize(build_concurrency, {});
dispatch_blocks[stream_index] = block;
block_size_to_be_inserted = 1;
}
else
{
dispatch_blocks = dispatchBlock(key_names_right, block);
}
assert(dispatch_blocks.size() == build_concurrency);
for (size_t j = stream_index; j < block_size_to_be_inserted + stream_index; ++j)
{
size_t i = j % build_concurrency;
if (!dispatch_blocks[i].rows())
{
continue;
}
{
const auto & join_partition = partitions[i];
auto partition_lock = join_partition->lockPartition();
join_partition->insertBlockForBuild(std::move(dispatch_blocks[i]));
/// to release memory before insert if already marked spill
checkAndMarkPartitionSpilledIfNeededInternal(*join_partition, partition_lock, i, stream_index);
if (!hash_join_spill_context->isPartitionSpilled(i))
{
bool meet_resize_exception = false;
try
{
insertFromBlockInternal(join_partition->getLastBuildBlock(), i);
join_partition->updateHashMapAndPoolMemoryUsage();
}
catch (ResizeException &)
{
meet_resize_exception = true;
LOG_DEBUG(log, "Meet resize exception when insert into partition {}", i);
}
/// double check here to release memory
checkAndMarkPartitionSpilledIfNeededInternal(*join_partition, partition_lock, i, stream_index);
if (meet_resize_exception)
RUNTIME_CHECK_MSG(
hash_join_spill_context->isPartitionSpilled(i),
"resize exception must trigger partition to spill");
}
}
if (auto_spill_trigger != nullptr)
auto_spill_trigger->triggerAutoSpill();
}
if (!hash_join_spill_context->isInAutoSpillMode())
spillMostMemoryUsedPartitionIfNeed(stream_index);
if (log->is(Poco::Message::PRIO_DEBUG))
{
auto total_bytes = getTotalByteCount();
if (total_bytes > 100 * 1024 * 1024)
LOG_DEBUG(
log,
fmt::format(
"all bytes used after one insert: {}, hash table and pool size: {}",
getTotalByteCount(),
getTotalHashTableAndPoolByteCount()));
}
}
}
bool Join::isEnableSpill() const
{
return hash_join_spill_context->isSpillEnabled();
}
bool Join::isRestoreJoin() const
{
return restore_round > 0;
}
void Join::insertFromBlockInternal(Block * stored_block, size_t stream_index)
{
size_t keys_size = key_names_right.size();
const Block & block = *stored_block;
size_t rows = block.rows();
/// Rare case, when keys are constant. To avoid code bloat, simply materialize them.
/// Note: this variable can't be removed because it will take smart pointers' lifecycle to the end of this function.
Columns materialized_columns;
ColumnRawPtrs key_columns = extractAndMaterializeKeyColumns(block, materialized_columns, key_names_right);
if (isNullAwareSemiFamily(kind))
{
if (rows > 0 && right_table_is_empty.load(std::memory_order_acquire))
right_table_is_empty.store(false, std::memory_order_release);
if (strictness == ASTTableJoin::Strictness::Any)
{
if (!right_has_all_key_null_row.load(std::memory_order_acquire))
{
/// Note that `extractAllKeyNullMap` must be done before `extractNestedColumnsAndNullMap`
/// because `extractNestedColumnsAndNullMap` will change the nullable column to its nested column.
ColumnPtr all_key_null_map_holder;
ConstNullMapPtr all_key_null_map{};
extractAllKeyNullMap(key_columns, all_key_null_map_holder, all_key_null_map);
if (all_key_null_map)
{
for (UInt8 is_null : *all_key_null_map)
{
if (is_null)
{
right_has_all_key_null_row.store(true, std::memory_order_release);
break;
}
}
}
}
}
}
/// We will insert to the map only keys, where all components are not NULL.
ColumnPtr null_map_holder;
ConstNullMapPtr null_map{};
extractNestedColumnsAndNullMap(key_columns, null_map_holder, null_map);
/// Reuse null_map to record the filtered rows, the rows contains NULL or does not
/// match the join filter will not insert to the maps
recordFilteredRows(block, non_equal_conditions.right_filter_column, null_map_holder, null_map);
if (needScanHashMapAfterProbe(kind))
{
/** Move the key columns to the beginning of the block.
* This is where ScanHashMapAfterProbBlockInputStream will expect.
*/
size_t key_num = 0;
for (const auto & name : key_names_right)
{
size_t pos = stored_block->getPositionByName(name);
ColumnWithTypeAndName col = stored_block->safeGetByPosition(pos);
stored_block->erase(pos);
stored_block->insert(key_num, std::move(col));
++key_num;
}
}
else
{
/// Remove the key columns from stored_block, as they are not needed.
for (const auto & name : key_names_right)
stored_block->erase(stored_block->getPositionByName(name));
}
size_t size = stored_block->columns();
/// Rare case, when joined columns are constant. To avoid code bloat, simply materialize them.
for (size_t i = 0; i < size; ++i)
{
ColumnPtr col = stored_block->safeGetByPosition(i).column;
if (ColumnPtr converted = col->convertToFullColumnIfConst())
stored_block->safeGetByPosition(i).column = converted;
}
/// In case of LEFT and FULL joins, if use_nulls, convert joined columns to Nullable.
if (isLeftOuterJoin(kind) || kind == ASTTableJoin::Kind::Full)
{
for (size_t i = getFullness(kind) ? keys_size : 0; i < size; ++i)
{
convertColumnToNullable(stored_block->getByPosition(i));
}
}
bool enable_join_spill = hash_join_spill_context->isSpillEnabled();
if (!isCrossJoin(kind))
{
if (enable_join_spill)
assert(partitions[stream_index]->getPartitionPool() != nullptr);
/// Fill the hash table.
JoinPartition::insertBlockIntoMaps(
partitions,
rows,
key_columns,
key_sizes,
collators,
stored_block,
null_map,
stream_index,
getBuildConcurrency(),
enable_fine_grained_shuffle,
enable_join_spill);
}
// generator in runtime filter
generateRuntimeFilterValues(block);
}
void Join::generateRuntimeFilterValues(const Block & block)
{
LOG_TRACE(log, "begin to generate rf values for one block in join id, block rows:{}", block.rows());
for (const auto & rf : runtime_filter_list)
{
auto column_with_type_and_name = block.getByName(rf->getSourceColumnName());
LOG_TRACE(log, "update rf values in join, values size:{}", column_with_type_and_name.column->size());
rf->updateValues(column_with_type_and_name, log);
}
}
void Join::finalizeRuntimeFilter()
{
for (const auto & rf : runtime_filter_list)
{
rf->finalize(log);
}
}
void Join::cancelRuntimeFilter(const String & reason)
{
for (const auto & rf : runtime_filter_list)
{
rf->cancel(log, reason);
}
}
void mergeNullAndFilterResult(
Block & block,
ColumnVector<UInt8>::Container & filter_column,
const String & filter_column_name,
bool null_as_true)
{
if (filter_column_name.empty())
return;
ColumnPtr current_filter_column = block.getByName(filter_column_name).column;
auto [filter_vec, nullmap_vec] = getDataAndNullMapVectorFromFilterColumn(current_filter_column);
if (nullmap_vec != nullptr)
{
for (size_t i = 0; i < nullmap_vec->size(); ++i)
{
if (filter_column[i] == 0)
continue;
if ((*nullmap_vec)[i])
filter_column[i] = null_as_true;
else
filter_column[i] = filter_column[i] && (*filter_vec)[i];
}
}
else
{
for (size_t i = 0; i < filter_vec->size(); ++i)
filter_column[i] = filter_column[i] && (*filter_vec)[i];
}
}
/**
* handle other join conditions
* Join Kind/Strictness ALL ANY
* INNER TiDB inner join TiDB semi join
* LEFT TiDB left join should not happen
* RIGHT TiDB right join should not happen
* RIGHT_SEMI/ANTI TiDB semi/anti join should not happen
* ANTI should not happen TiDB anti semi join
* @param block
* @param offsets_to_replicate
* @param left_table_columns
* @param right_table_columns
*/
void Join::handleOtherConditions(
Block & block,
std::unique_ptr<IColumn::Filter> & anti_filter,
std::unique_ptr<IColumn::Offsets> & offsets_to_replicate,
const std::vector<size_t> & right_table_columns) const
{
non_equal_conditions.other_cond_expr->execute(block);
auto filter_column = ColumnUInt8::create();
auto & filter = filter_column->getData();
filter.assign(block.rows(), static_cast<UInt8>(1));
mergeNullAndFilterResult(block, filter, non_equal_conditions.other_cond_name, false);
ColumnUInt8::Container row_filter(filter.size(), 0);
if (isLeftOuterSemiFamily(kind))
{
const auto helper_pos = block.getPositionByName(match_helper_name);
const auto * old_match_nullable
= checkAndGetColumn<ColumnNullable>(block.safeGetByPosition(helper_pos).column.get());
const auto & old_match_vec
= static_cast<const ColumnVector<Int8> *>(old_match_nullable->getNestedColumnPtr().get())->getData();
{
/// we assume there is no null value in the `match-helper` column after adder<>().
if (!mem_utils::memoryIsZero(
old_match_nullable->getNullMapData().data(),
old_match_nullable->getNullMapData().size()))
throw Exception("T here shouldn't be null before merging other conditions.", ErrorCodes::LOGICAL_ERROR);
}
const auto rows = offsets_to_replicate->size();
if (old_match_vec.size() != rows)
throw Exception(
"Size of column match-helper must be equal to column size of left block.",
ErrorCodes::LOGICAL_ERROR);
auto match_col = ColumnInt8::create(rows, 0);
auto & match_vec = match_col->getData();
auto match_nullmap = ColumnUInt8::create(rows, 0);
auto & match_nullmap_vec = match_nullmap->getData();
/// nullmap and data of `other_eq_filter_from_in_column`.
const ColumnUInt8::Container *eq_in_vec = nullptr, *eq_in_nullmap = nullptr;
ColumnPtr eq_in_column = nullptr;
if (!non_equal_conditions.other_eq_cond_from_in_name.empty())
{
eq_in_column = block.getByName(non_equal_conditions.other_eq_cond_from_in_name).column;
auto data_and_null_map_vec = getDataAndNullMapVectorFromFilterColumn(eq_in_column);
eq_in_vec = data_and_null_map_vec.first;
eq_in_nullmap = data_and_null_map_vec.second;
}
/// for (anti)leftOuterSemi join, we should keep only one row for each original row of left table.
/// and because it is semi join, we needn't save columns of right table, so we just keep the first replica.
for (size_t i = 0; i < offsets_to_replicate->size(); ++i)
{
size_t prev_offset = i > 0 ? (*offsets_to_replicate)[i - 1] : 0;
size_t current_offset = (*offsets_to_replicate)[i];
row_filter[prev_offset] = 1;
if (old_match_vec[i] == 0)
continue;
/// fill match_vec and match_nullmap_vec
/// if there is `1` in filter, match_vec is 1.
/// if there is `null` in eq_in_nullmap, match_nullmap_vec is 1.
/// else, match_vec is 0.
bool has_row_matched = false, has_row_null = false;
for (size_t index = prev_offset; index < current_offset; index++)
{
if (!filter[index])
continue;
if (eq_in_nullmap && (*eq_in_nullmap)[index])
has_row_null = true;
else if (!eq_in_vec || (*eq_in_vec)[index])
{
has_row_matched = true;
break;
}
}
if (has_row_matched)
match_vec[i] = 1;
else if (has_row_null)
match_nullmap_vec[i] = 1;
}
for (size_t i = 0; i < block.columns(); ++i)
if (i != helper_pos)
block.getByPosition(i).column = block.getByPosition(i).column->filter(row_filter, -1);
block.safeGetByPosition(helper_pos).column
= ColumnNullable::create(std::move(match_col), std::move(match_nullmap));
return;
}
/// other_eq_filter_from_in_column is used in anti semi join:
/// if there is a row that return null or false for other_condition, then for anti semi join, this row should be returned.
/// otherwise, it will check other_eq_filter_from_in_column, if other_eq_filter_from_in_column return false, this row should
/// be returned, if other_eq_filter_from_in_column return true or null this row should not be returned.
mergeNullAndFilterResult(block, filter, non_equal_conditions.other_eq_cond_from_in_name, isAntiJoin(kind));
if ((isInnerJoin(kind) && original_strictness == ASTTableJoin::Strictness::All)
|| isNecessaryKindToUseRowFlaggedHashMap(kind))
{
/// inner | rightSemi | rightAnti | rightOuter join, just use other_filter_column to filter result
for (size_t i = 0; i < block.columns(); ++i)
block.safeGetByPosition(i).column = block.safeGetByPosition(i).column->filter(filter, -1);
return;
}
for (size_t i = 0, prev_offset = 0; i < offsets_to_replicate->size(); ++i)
{
size_t current_offset = (*offsets_to_replicate)[i];
bool has_row_kept = false;
for (size_t index = prev_offset; index < current_offset; index++)
{
if (original_strictness == ASTTableJoin::Strictness::Any)
{
/// for semi/anti join, at most one row is kept
row_filter[index] = !has_row_kept && filter[index];
}
else
{
/// original strictness = ALL && kind = Anti should not happen
row_filter[index] = filter[index];
}
if (row_filter[index])
has_row_kept = true;
}
if (prev_offset < current_offset)
{
/// for outer join, at least one row must be kept
if (isLeftOuterJoin(kind) && !has_row_kept)
row_filter[prev_offset] = 1;
if (isAntiJoin(kind))
{
if (has_row_kept && !(*anti_filter)[i])
/// anti_filter=false means equal condition is matched,
/// has_row_kept=true means other condition is matched,
/// for anti join, we should not return any rows when the both conditions are matched.
for (size_t index = prev_offset; index < current_offset; index++)
row_filter[index] = 0;
else
/// when there is a condition not matched, we should return this row.
row_filter[prev_offset] = 1;
}
}
prev_offset = current_offset;
}
if (isLeftOuterJoin(kind))
{
/// for left join, convert right column to null if not joined
for (size_t right_table_column : right_table_columns)
{
auto & column = block.getByPosition(right_table_column);
auto full_column
= column.column->isColumnConst() ? column.column->convertToFullColumnIfConst() : column.column;
if (!full_column->isColumnNullable())
{
throw Exception("Should not reach here, the right table column for left join must be nullable");
}
auto current_column = full_column;
auto result_column = (*std::move(current_column)).mutate();
static_cast<ColumnNullable &>(*result_column).applyNegatedNullMap(*filter_column);
column.column = std::move(result_column);
}
for (size_t i = 0; i < block.columns(); ++i)
block.getByPosition(i).column = block.getByPosition(i).column->filter(row_filter, -1);
return;
}
if (isInnerJoin(kind) || isAntiJoin(kind))
{