-
Notifications
You must be signed in to change notification settings - Fork 411
/
Copy pathAggregator.cpp
2561 lines (2196 loc) · 92.7 KB
/
Aggregator.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 <AggregateFunctions/AggregateFunctionArray.h>
#include <AggregateFunctions/AggregateFunctionState.h>
#include <Common/FailPoint.h>
#include <Common/Stopwatch.h>
#include <Common/ThresholdUtils.h>
#include <Common/typeid_cast.h>
#include <DataStreams/AggHashTableToBlocksBlockInputStream.h>
#include <DataStreams/materializeBlock.h>
#include <DataTypes/DataTypeAggregateFunction.h>
#include <DataTypes/DataTypeNullable.h>
#include <Interpreters/Aggregator.h>
#include <array>
#include <cassert>
namespace DB
{
namespace ErrorCodes
{
extern const int UNKNOWN_AGGREGATED_DATA_VARIANT;
extern const int EMPTY_DATA_PASSED;
extern const int CANNOT_MERGE_DIFFERENT_AGGREGATED_DATA_VARIANTS;
extern const int LOGICAL_ERROR;
} // namespace ErrorCodes
namespace FailPoints
{
extern const char random_aggregate_create_state_failpoint[];
extern const char random_aggregate_merge_failpoint[];
extern const char force_agg_on_partial_block[];
extern const char random_fail_in_resize_callback[];
} // namespace FailPoints
#define AggregationMethodName(NAME) AggregatedDataVariants::AggregationMethod_##NAME
#define AggregationMethodNameTwoLevel(NAME) AggregatedDataVariants::AggregationMethod_##NAME##_two_level
#define AggregationMethodType(NAME) AggregatedDataVariants::Type::NAME
#define AggregationMethodTypeTwoLevel(NAME) AggregatedDataVariants::Type::NAME##_two_level
#define ToAggregationMethodPtr(NAME, ptr) (reinterpret_cast<AggregationMethodName(NAME) *>(ptr))
#define ToAggregationMethodPtrTwoLevel(NAME, ptr) (reinterpret_cast<AggregationMethodNameTwoLevel(NAME) *>(ptr))
AggregatedDataVariants::~AggregatedDataVariants()
{
if (aggregator && !aggregator->all_aggregates_has_trivial_destructor)
{
try
{
aggregator->destroyAllAggregateStates(*this);
}
catch (...)
{
tryLogCurrentException(aggregator->log, __PRETTY_FUNCTION__);
}
}
destroyAggregationMethodImpl();
}
bool AggregatedDataVariants::tryMarkNeedSpill()
{
assert(!need_spill);
if (empty())
return false;
if (!isTwoLevel())
{
/// Data can only be flushed to disk if a two-level aggregation is supported.
if (!isConvertibleToTwoLevel())
return false;
convertToTwoLevel();
}
need_spill = true;
return true;
}
void AggregatedDataVariants::destroyAggregationMethodImpl()
{
if (!aggregation_method_impl)
return;
#define M(NAME, IS_TWO_LEVEL) \
case AggregationMethodType(NAME): \
{ \
delete reinterpret_cast<AggregationMethodName(NAME) *>(aggregation_method_impl); \
aggregation_method_impl = nullptr; \
break; \
}
switch (type)
{
APPLY_FOR_AGGREGATED_VARIANTS(M)
default:
break;
}
#undef M
}
void AggregatedDataVariants::init(Type variants_type)
{
destroyAggregationMethodImpl();
switch (variants_type)
{
case Type::EMPTY:
break;
case Type::without_key:
break;
#define M(NAME, IS_TWO_LEVEL) \
case AggregationMethodType(NAME): \
{ \
aggregation_method_impl = std::make_unique<AggregationMethodName(NAME)>().release(); \
break; \
}
APPLY_FOR_AGGREGATED_VARIANTS(M)
#undef M
default:
throw Exception("Unknown aggregated data variant.", ErrorCodes::UNKNOWN_AGGREGATED_DATA_VARIANT);
}
type = variants_type;
}
size_t AggregatedDataVariants::getBucketNumberForTwoLevelHashTable(Type type)
{
switch (type)
{
#define M(NAME) \
case AggregationMethodType(NAME): \
{ \
return AggregationMethodNameTwoLevel(NAME)::Data::NUM_BUCKETS; \
}
APPLY_FOR_VARIANTS_CONVERTIBLE_TO_TWO_LEVEL(M)
#undef M
default:
throw Exception("Wrong data variant passed.", ErrorCodes::LOGICAL_ERROR);
}
}
void AggregatedDataVariants::setResizeCallbackIfNeeded(size_t thread_num) const
{
if (aggregator)
{
auto agg_spill_context = aggregator->agg_spill_context;
if (agg_spill_context->isSpillEnabled() && agg_spill_context->isInAutoSpillMode())
{
auto resize_callback = [agg_spill_context, thread_num]() {
if (agg_spill_context->supportFurtherSpill()
&& agg_spill_context->isThreadMarkedForAutoSpill(thread_num))
return false;
bool ret = true;
fiu_do_on(FailPoints::random_fail_in_resize_callback, {
if (agg_spill_context->supportFurtherSpill())
{
ret = !agg_spill_context->markThreadForAutoSpill(thread_num);
}
});
return ret;
};
#define M(NAME) \
case AggregationMethodType(NAME): \
{ \
ToAggregationMethodPtr(NAME, aggregation_method_impl)->data.setResizeCallback(resize_callback); \
break; \
}
switch (type)
{
APPLY_FOR_VARIANTS_TWO_LEVEL(M)
default:
throw Exception("Unknown aggregated data variant.", ErrorCodes::UNKNOWN_AGGREGATED_DATA_VARIANT);
}
#undef M
}
}
}
void AggregatedDataVariants::convertToTwoLevel()
{
switch (type)
{
#define M(NAME) \
case AggregationMethodType(NAME): \
{ \
if (aggregator) \
LOG_TRACE( \
aggregator->log, \
"Converting aggregation data type `{}` to `{}`.", \
getMethodName(AggregationMethodType(NAME)), \
getMethodName(AggregationMethodTypeTwoLevel(NAME))); \
auto ori_ptr = ToAggregationMethodPtr(NAME, aggregation_method_impl); \
auto two_level = std::make_unique<AggregationMethodNameTwoLevel(NAME)>(*ori_ptr); \
delete ori_ptr; \
aggregation_method_impl = two_level.release(); \
type = AggregationMethodTypeTwoLevel(NAME); \
break; \
}
APPLY_FOR_VARIANTS_CONVERTIBLE_TO_TWO_LEVEL(M)
#undef M
default:
throw Exception("Wrong data variant passed.", ErrorCodes::LOGICAL_ERROR);
}
aggregator->useTwoLevelHashTable();
}
Block Aggregator::getHeader(bool final) const
{
return params.getHeader(final);
}
Block Aggregator::Params::getHeader(
const Block & src_header,
const Block & intermediate_header,
const ColumnNumbers & keys,
const AggregateDescriptions & aggregates,
bool final)
{
Block res;
if (intermediate_header)
{
res = intermediate_header.cloneEmpty();
if (final)
{
for (const auto & aggregate : aggregates)
{
auto & elem = res.getByName(aggregate.column_name);
elem.type = aggregate.function->getReturnType();
elem.column = elem.type->createColumn();
}
}
}
else
{
for (const auto & key : keys)
res.insert(src_header.safeGetByPosition(key).cloneEmpty());
for (const auto & aggregate : aggregates)
{
size_t arguments_size = aggregate.arguments.size();
DataTypes argument_types(arguments_size);
for (size_t j = 0; j < arguments_size; ++j)
argument_types[j] = src_header.safeGetByPosition(aggregate.arguments[j]).type;
DataTypePtr type;
if (final)
type = aggregate.function->getReturnType();
else
type = std::make_shared<DataTypeAggregateFunction>(
aggregate.function,
argument_types,
aggregate.parameters);
res.insert({type, aggregate.column_name});
}
}
return materializeBlock(res);
}
Aggregator::Aggregator(
const Params & params_,
const String & req_id,
size_t concurrency,
const RegisterOperatorSpillContext & register_operator_spill_context)
: params(params_)
, log(Logger::get(req_id))
, is_cancelled([]() { return false; })
{
aggregate_functions.resize(params.aggregates_size);
for (size_t i = 0; i < params.aggregates_size; ++i)
aggregate_functions[i] = params.aggregates[i].function.get();
/// Initialize sizes of aggregation states and its offsets.
offsets_of_aggregate_states.resize(params.aggregates_size);
total_size_of_aggregate_states = 0;
all_aggregates_has_trivial_destructor = true;
// aggreate_states will be aligned as below:
// |<-- state_1 -->|<-- pad_1 -->|<-- state_2 -->|<-- pad_2 -->| .....
//
// pad_N will be used to match alignment requirement for each next state.
// The address of state_1 is aligned based on maximum alignment requirements in states
for (size_t i = 0; i < params.aggregates_size; ++i)
{
offsets_of_aggregate_states[i] = total_size_of_aggregate_states;
total_size_of_aggregate_states += params.aggregates[i].function->sizeOfData();
// aggreate states are aligned based on maximum requirement
align_aggregate_states = std::max(align_aggregate_states, params.aggregates[i].function->alignOfData());
// If not the last aggregate_state, we need pad it so that next aggregate_state will be aligned.
if (i + 1 < params.aggregates_size)
{
size_t alignment_of_next_state = params.aggregates[i + 1].function->alignOfData();
if ((alignment_of_next_state & (alignment_of_next_state - 1)) != 0)
throw Exception("Logical error: alignOfData is not 2^N", ErrorCodes::LOGICAL_ERROR);
/// Extend total_size to next alignment requirement
/// Add padding by rounding up 'total_size_of_aggregate_states' to be a multiplier of alignment_of_next_state.
total_size_of_aggregate_states = (total_size_of_aggregate_states + alignment_of_next_state - 1)
/ alignment_of_next_state * alignment_of_next_state;
}
if (!params.aggregates[i].function->hasTrivialDestructor())
all_aggregates_has_trivial_destructor = false;
}
method_chosen = chooseAggregationMethod();
RUNTIME_CHECK_MSG(method_chosen != AggregatedDataVariants::Type::EMPTY, "Invalid aggregation method");
agg_spill_context = std::make_shared<AggSpillContext>(
concurrency,
params.spill_config,
params.getMaxBytesBeforeExternalGroupBy(),
log);
if (agg_spill_context->supportSpill())
{
bool is_convertible_to_two_level = AggregatedDataVariants::isConvertibleToTwoLevel(method_chosen);
if (!is_convertible_to_two_level)
{
params.setMaxBytesBeforeExternalGroupBy(0);
agg_spill_context->disableSpill();
if (method_chosen != AggregatedDataVariants::Type::without_key)
LOG_WARNING(
log,
"Aggregation does not support spill because aggregator hash table does not support two level");
}
}
if (register_operator_spill_context != nullptr)
register_operator_spill_context(agg_spill_context);
if (agg_spill_context->isSpillEnabled())
{
/// init spiller if needed
/// for aggregation, the input block is sorted by bucket number
/// so it can work with MergingAggregatedMemoryEfficientBlockInputStream
agg_spill_context->buildSpiller(getHeader(false));
}
}
inline bool IsTypeNumber64(const DataTypePtr & type)
{
return type->isNumber() && type->getSizeOfValueInMemory() == sizeof(uint64_t);
}
#define APPLY_FOR_AGG_FAST_PATH_TYPES(M) \
M(Number64) \
M(StringBin) \
M(StringBinPadding)
enum class AggFastPathType
{
#define M(NAME) NAME,
APPLY_FOR_AGG_FAST_PATH_TYPES(M)
#undef M
};
AggregatedDataVariants::Type ChooseAggregationMethodTwoKeys(const AggFastPathType * fast_path_types)
{
auto tp1 = fast_path_types[0];
auto tp2 = fast_path_types[1];
switch (tp1)
{
case AggFastPathType::Number64:
{
switch (tp2)
{
case AggFastPathType::Number64:
return AggregatedDataVariants::Type::serialized; // unreachable. keys64 or keys128 will be used before
case AggFastPathType::StringBin:
return AggregatedDataVariants::Type::two_keys_num64_strbin;
case AggFastPathType::StringBinPadding:
return AggregatedDataVariants::Type::two_keys_num64_strbinpadding;
}
}
case AggFastPathType::StringBin:
{
switch (tp2)
{
case AggFastPathType::Number64:
return AggregatedDataVariants::Type::two_keys_strbin_num64;
case AggFastPathType::StringBin:
return AggregatedDataVariants::Type::two_keys_strbin_strbin;
case AggFastPathType::StringBinPadding:
return AggregatedDataVariants::Type::serialized; // rare case
}
}
case AggFastPathType::StringBinPadding:
{
switch (tp2)
{
case AggFastPathType::Number64:
return AggregatedDataVariants::Type::two_keys_strbinpadding_num64;
case AggFastPathType::StringBin:
return AggregatedDataVariants::Type::serialized; // rare case
case AggFastPathType::StringBinPadding:
return AggregatedDataVariants::Type::two_keys_strbinpadding_strbinpadding;
}
}
}
}
// return AggregatedDataVariants::Type::serialized if can NOT determine fast path.
AggregatedDataVariants::Type ChooseAggregationMethodFastPath(
size_t keys_size,
const DataTypes & types_not_null,
const TiDB::TiDBCollators & collators)
{
std::array<AggFastPathType, 2> fast_path_types{};
if (keys_size == fast_path_types.max_size())
{
for (size_t i = 0; i < keys_size; ++i)
{
const auto & type = types_not_null[i];
if (type->isString())
{
if (collators.empty() || !collators[i])
{
// use original way
return AggregatedDataVariants::Type::serialized;
}
else
{
switch (collators[i]->getCollatorType())
{
case TiDB::ITiDBCollator::CollatorType::UTF8MB4_BIN:
case TiDB::ITiDBCollator::CollatorType::UTF8_BIN:
case TiDB::ITiDBCollator::CollatorType::LATIN1_BIN:
case TiDB::ITiDBCollator::CollatorType::ASCII_BIN:
{
fast_path_types[i] = AggFastPathType::StringBinPadding;
break;
}
case TiDB::ITiDBCollator::CollatorType::BINARY:
{
fast_path_types[i] = AggFastPathType::StringBin;
break;
}
default:
{
// for CI COLLATION, use original way
return AggregatedDataVariants::Type::serialized;
}
}
}
}
else if (IsTypeNumber64(type))
{
fast_path_types[i] = AggFastPathType::Number64;
}
else
{
return AggregatedDataVariants::Type::serialized;
}
}
return ChooseAggregationMethodTwoKeys(fast_path_types.data());
}
return AggregatedDataVariants::Type::serialized;
}
AggregatedDataVariants::Type Aggregator::chooseAggregationMethod()
{
/// If no keys. All aggregating to single row.
if (params.keys_size == 0)
return AggregatedDataVariants::Type::without_key;
/// Check if at least one of the specified keys is nullable.
DataTypes types_removed_nullable;
types_removed_nullable.reserve(params.keys.size());
bool has_nullable_key = false;
for (const auto & pos : params.keys)
{
const auto & type
= (params.src_header ? params.src_header : params.intermediate_header).safeGetByPosition(pos).type;
if (type->isNullable())
{
has_nullable_key = true;
types_removed_nullable.push_back(removeNullable(type));
}
else
types_removed_nullable.push_back(type);
}
/** Returns ordinary (not two-level) methods, because we start from them.
* Later, during aggregation process, data may be converted (partitioned) to two-level structure, if cardinality is high.
*/
size_t keys_bytes = 0;
size_t num_fixed_contiguous_keys = 0;
key_sizes.resize(params.keys_size);
for (size_t j = 0; j < params.keys_size; ++j)
{
if (types_removed_nullable[j]->isValueUnambiguouslyRepresentedInContiguousMemoryRegion())
{
if (types_removed_nullable[j]->isValueUnambiguouslyRepresentedInFixedSizeContiguousMemoryRegion()
&& (params.collators.empty() || params.collators[j] == nullptr))
{
++num_fixed_contiguous_keys;
key_sizes[j] = types_removed_nullable[j]->getSizeOfValueInMemory();
keys_bytes += key_sizes[j];
}
}
}
if (has_nullable_key)
{
if (params.keys_size == num_fixed_contiguous_keys)
{
/// Pack if possible all the keys along with information about which key values are nulls
/// into a fixed 16- or 32-byte blob.
if (std::tuple_size<KeysNullMap<UInt128>>::value + keys_bytes <= 16)
return AggregatedDataVariants::Type::nullable_keys128;
if (std::tuple_size<KeysNullMap<UInt256>>::value + keys_bytes <= 32)
return AggregatedDataVariants::Type::nullable_keys256;
}
/// Fallback case.
return AggregatedDataVariants::Type::serialized;
}
/// No key has been found to be nullable.
const DataTypes & types_not_null = types_removed_nullable;
assert(!has_nullable_key);
/// Single numeric key.
if (params.keys_size == 1 && types_not_null[0]->isValueRepresentedByNumber())
{
size_t size_of_field = types_not_null[0]->getSizeOfValueInMemory();
if (size_of_field == 1)
return AggregatedDataVariants::Type::key8;
if (size_of_field == 2)
return AggregatedDataVariants::Type::key16;
if (size_of_field == 4)
return AggregatedDataVariants::Type::key32;
if (size_of_field == 8)
return AggregatedDataVariants::Type::key64;
if (size_of_field == 16)
return AggregatedDataVariants::Type::keys128;
if (size_of_field == 32)
return AggregatedDataVariants::Type::keys256;
if (size_of_field == sizeof(Decimal256))
return AggregatedDataVariants::Type::key_int256;
throw Exception(
"Logical error: numeric column has sizeOfField not in 1, 2, 4, 8, 16, 32.",
ErrorCodes::LOGICAL_ERROR);
}
/// If all keys fits in N bits, will use hash table with all keys packed (placed contiguously) to single N-bit key.
if (params.keys_size == num_fixed_contiguous_keys)
{
if (keys_bytes <= 2)
return AggregatedDataVariants::Type::keys16;
if (keys_bytes <= 4)
return AggregatedDataVariants::Type::keys32;
if (keys_bytes <= 8)
return AggregatedDataVariants::Type::keys64;
if (keys_bytes <= 16)
return AggregatedDataVariants::Type::keys128;
if (keys_bytes <= 32)
return AggregatedDataVariants::Type::keys256;
}
/// If single string key - will use hash table with references to it. Strings itself are stored separately in Arena.
if (params.keys_size == 1 && types_not_null[0]->isString())
{
if (params.collators.empty() || !params.collators[0])
{
// use original way. `Type::one_key_strbin` will generate empty column.
return AggregatedDataVariants::Type::key_string;
}
else
{
switch (params.collators[0]->getCollatorType())
{
case TiDB::ITiDBCollator::CollatorType::UTF8MB4_BIN:
case TiDB::ITiDBCollator::CollatorType::UTF8_BIN:
case TiDB::ITiDBCollator::CollatorType::LATIN1_BIN:
case TiDB::ITiDBCollator::CollatorType::ASCII_BIN:
{
return AggregatedDataVariants::Type::one_key_strbinpadding;
}
case TiDB::ITiDBCollator::CollatorType::BINARY:
{
return AggregatedDataVariants::Type::one_key_strbin;
}
default:
{
// for CI COLLATION, use original way
return AggregatedDataVariants::Type::key_string;
}
}
}
}
if (params.keys_size == 1 && types_not_null[0]->isFixedString())
return AggregatedDataVariants::Type::key_fixed_string;
return ChooseAggregationMethodFastPath(params.keys_size, types_not_null, params.collators);
}
void Aggregator::createAggregateStates(AggregateDataPtr & aggregate_data) const
{
for (size_t j = 0; j < params.aggregates_size; ++j)
{
try
{
/** An exception may occur if there is a shortage of memory.
* In order that then everything is properly destroyed, we "roll back" some of the created states.
* The code is not very convenient.
*/
FAIL_POINT_TRIGGER_EXCEPTION(FailPoints::random_aggregate_create_state_failpoint);
aggregate_functions[j]->create(aggregate_data + offsets_of_aggregate_states[j]);
}
catch (...)
{
for (size_t rollback_j = 0; rollback_j < j; ++rollback_j)
aggregate_functions[rollback_j]->destroy(aggregate_data + offsets_of_aggregate_states[rollback_j]);
throw;
}
}
}
/** It's interesting - if you remove `noinline`, then gcc for some reason will inline this function, and the performance decreases (~ 10%).
* (Probably because after the inline of this function, more internal functions no longer be inlined.)
* Inline does not make sense, since the inner loop is entirely inside this function.
*/
template <typename Method>
void NO_INLINE Aggregator::executeImpl(
Method & method,
Arena * aggregates_pool,
AggProcessInfo & agg_process_info,
TiDB::TiDBCollators & collators) const
{
typename Method::State state(agg_process_info.key_columns, key_sizes, collators);
executeImplBatch(method, state, aggregates_pool, agg_process_info);
}
template <typename Method>
std::optional<typename Method::EmplaceResult> Aggregator::emplaceKey(
Method & method,
typename Method::State & state,
size_t index,
Arena & aggregates_pool,
std::vector<std::string> & sort_key_containers) const
{
try
{
return state.emplaceKey(method.data, index, aggregates_pool, sort_key_containers);
}
catch (ResizeException &)
{
return {};
}
}
template <typename Method>
ALWAYS_INLINE void Aggregator::executeImplBatch(
Method & method,
typename Method::State & state,
Arena * aggregates_pool,
AggProcessInfo & agg_process_info) const
{
std::vector<std::string> sort_key_containers;
sort_key_containers.resize(params.keys_size, "");
size_t agg_size = agg_process_info.end_row - agg_process_info.start_row;
fiu_do_on(FailPoints::force_agg_on_partial_block, {
if (agg_size > 0 && agg_process_info.start_row == 0)
agg_size = std::max(agg_size / 2, 1);
});
/// Optimization for special case when there are no aggregate functions.
if (params.aggregates_size == 0)
{
/// For all rows.
AggregateDataPtr place = aggregates_pool->alloc(0);
for (size_t i = 0; i < agg_size; ++i)
{
auto emplace_result_hold
= emplaceKey(method, state, agg_process_info.start_row, *aggregates_pool, sort_key_containers);
if likely (emplace_result_hold.has_value())
{
emplace_result_hold.value().setMapped(place);
++agg_process_info.start_row;
}
else
{
LOG_INFO(log, "HashTable resize throw ResizeException since the data is already marked for spill");
break;
}
}
return;
}
/// Optimization for special case when aggregating by 8bit key.
if constexpr (std::is_same_v<Method, AggregatedDataVariants::AggregationMethod_key8>)
{
for (AggregateFunctionInstruction * inst = agg_process_info.aggregate_functions_instructions.data(); inst->that;
++inst)
{
inst->batch_that->addBatchLookupTable8(
agg_process_info.start_row,
agg_size,
reinterpret_cast<AggregateDataPtr *>(method.data.data()),
inst->state_offset,
[&](AggregateDataPtr & aggregate_data) {
aggregate_data
= aggregates_pool->alignedAlloc(total_size_of_aggregate_states, align_aggregate_states);
createAggregateStates(aggregate_data);
},
state.getKeyData(),
inst->batch_arguments,
aggregates_pool);
}
agg_process_info.start_row += agg_size;
return;
}
/// Generic case.
std::unique_ptr<AggregateDataPtr[]> places(new AggregateDataPtr[agg_size]);
std::optional<size_t> processed_rows;
for (size_t i = agg_process_info.start_row; i < agg_process_info.start_row + agg_size; ++i)
{
AggregateDataPtr aggregate_data = nullptr;
auto emplace_result_holder = emplaceKey(method, state, i, *aggregates_pool, sort_key_containers);
if unlikely (!emplace_result_holder.has_value())
{
LOG_INFO(log, "HashTable resize throw ResizeException since the data is already marked for spill");
break;
}
auto & emplace_result = emplace_result_holder.value();
/// If a new key is inserted, initialize the states of the aggregate functions, and possibly something related to the key.
if (emplace_result.isInserted())
{
/// exception-safety - if you can not allocate memory or create states, then destructors will not be called.
emplace_result.setMapped(nullptr);
aggregate_data = aggregates_pool->alignedAlloc(total_size_of_aggregate_states, align_aggregate_states);
createAggregateStates(aggregate_data);
emplace_result.setMapped(aggregate_data);
}
else
aggregate_data = emplace_result.getMapped();
places[i - agg_process_info.start_row] = aggregate_data;
processed_rows = i;
}
if (processed_rows)
{
/// Add values to the aggregate functions.
for (AggregateFunctionInstruction * inst = agg_process_info.aggregate_functions_instructions.data(); inst->that;
++inst)
{
inst->batch_that->addBatch(
agg_process_info.start_row,
*processed_rows - agg_process_info.start_row + 1,
places.get(),
inst->state_offset,
inst->batch_arguments,
aggregates_pool);
}
agg_process_info.start_row = *processed_rows + 1;
}
}
void NO_INLINE
Aggregator::executeWithoutKeyImpl(AggregatedDataWithoutKey & res, AggProcessInfo & agg_process_info, Arena * arena)
{
size_t agg_size = agg_process_info.end_row - agg_process_info.start_row;
fiu_do_on(FailPoints::force_agg_on_partial_block, {
if (agg_size > 0 && agg_process_info.start_row == 0)
agg_size = std::max(agg_size / 2, 1);
});
/// Adding values
for (AggregateFunctionInstruction * inst = agg_process_info.aggregate_functions_instructions.data(); inst->that;
++inst)
{
inst->batch_that->addBatchSinglePlace(
agg_process_info.start_row,
agg_size,
res + inst->state_offset,
inst->batch_arguments,
arena);
}
agg_process_info.start_row += agg_size;
}
void Aggregator::prepareAggregateInstructions(
Columns columns,
AggregateColumns & aggregate_columns,
Columns & materialized_columns,
AggregateFunctionInstructions & aggregate_functions_instructions)
{
for (size_t i = 0; i < params.aggregates_size; ++i)
aggregate_columns[i].resize(params.aggregates[i].arguments.size());
aggregate_functions_instructions.resize(params.aggregates_size + 1);
aggregate_functions_instructions[params.aggregates_size].that = nullptr;
for (size_t i = 0; i < params.aggregates_size; ++i)
{
for (size_t j = 0; j < aggregate_columns[i].size(); ++j)
{
aggregate_columns[i][j] = columns.at(params.aggregates[i].arguments[j]).get();
if (ColumnPtr converted = aggregate_columns[i][j]->convertToFullColumnIfConst())
{
materialized_columns.push_back(converted);
aggregate_columns[i][j] = materialized_columns.back().get();
}
}
aggregate_functions_instructions[i].arguments = aggregate_columns[i].data();
aggregate_functions_instructions[i].state_offset = offsets_of_aggregate_states[i];
auto * that = aggregate_functions[i];
/// Unnest consecutive trailing -State combinators
while (const auto * func = typeid_cast<const AggregateFunctionState *>(that))
that = func->getNestedFunction().get();
aggregate_functions_instructions[i].that = that;
if (const auto * func = typeid_cast<const AggregateFunctionArray *>(that))
{
UNUSED(func);
throw Exception("Not support AggregateFunctionArray", ErrorCodes::NOT_IMPLEMENTED);
}
else
aggregate_functions_instructions[i].batch_arguments = aggregate_columns[i].data();
aggregate_functions_instructions[i].batch_that = that;
}
}
void Aggregator::AggProcessInfo::prepareForAgg()
{
if (prepare_for_agg_done)
return;
RUNTIME_CHECK_MSG(block, "Block must be set before execution aggregation");
start_row = 0;
end_row = block.rows();
input_columns = block.getColumns();
materialized_columns.reserve(aggregator->params.keys_size);
key_columns.resize(aggregator->params.keys_size);
aggregate_columns.resize(aggregator->params.aggregates_size);
/** Constant columns are not supported directly during aggregation.
* To make them work anyway, we materialize them.
*/
for (size_t i = 0; i < aggregator->params.keys_size; ++i)
{
key_columns[i] = input_columns.at(aggregator->params.keys[i]).get();
if (ColumnPtr converted = key_columns[i]->convertToFullColumnIfConst())
{
/// Remember the columns we will work with
materialized_columns.push_back(converted);
key_columns[i] = materialized_columns.back().get();
}
}
aggregator->prepareAggregateInstructions(
input_columns,
aggregate_columns,
materialized_columns,
aggregate_functions_instructions);
prepare_for_agg_done = true;
}
bool Aggregator::executeOnBlock(AggProcessInfo & agg_process_info, AggregatedDataVariants & result, size_t thread_num)
{
assert(!result.need_spill);
if (is_cancelled())
return true;
/// `result` will destroy the states of aggregate functions in the destructor
result.aggregator = this;
/// How to perform the aggregation?
if (!result.inited())
{
result.init(method_chosen);
result.keys_size = params.keys_size;
result.key_sizes = key_sizes;
LOG_TRACE(log, "Aggregation method: `{}`", result.getMethodName());
}
agg_process_info.prepareForAgg();
if (is_cancelled())
return true;
if (result.type == AggregatedDataVariants::Type::without_key && !result.without_key)
{
AggregateDataPtr place
= result.aggregates_pool->alignedAlloc(total_size_of_aggregate_states, align_aggregate_states);
createAggregateStates(place);
result.without_key = place;
}
/// We select one of the aggregation methods and call it.
assert(agg_process_info.start_row <= agg_process_info.end_row);
/// For the case when there are no keys (all aggregate into one row).
if (result.type == AggregatedDataVariants::Type::without_key)
{
executeWithoutKeyImpl(result.without_key, agg_process_info, result.aggregates_pool);
}
else
{
#define M(NAME, IS_TWO_LEVEL) \
case AggregationMethodType(NAME): \
{ \
executeImpl( \
*ToAggregationMethodPtr(NAME, result.aggregation_method_impl), \
result.aggregates_pool, \
agg_process_info, \
params.collators); \
break; \
}
switch (result.type)
{
APPLY_FOR_AGGREGATED_VARIANTS(M)
default:
break;
}
#undef M
}
size_t result_size = result.size();
auto result_size_bytes = result.bytesCount();
/// worth_convert_to_two_level is set to true if
/// 1. some other threads already convert to two level
/// 2. the result size exceeds threshold
bool worth_convert_to_two_level = use_two_level_hash_table
|| (group_by_two_level_threshold && result_size >= group_by_two_level_threshold)
|| (group_by_two_level_threshold_bytes && result_size_bytes >= group_by_two_level_threshold_bytes);
/** Converting to a two-level data structure.
* It allows you to make, in the subsequent, an effective merge - either economical from memory or parallel.
*/
if (result.isConvertibleToTwoLevel() && worth_convert_to_two_level)
{
result.convertToTwoLevel();
result.setResizeCallbackIfNeeded(thread_num);
}
/** Flush data to disk if too much RAM is consumed.
*/
auto revocable_bytes = result.revocableBytes();
if (revocable_bytes > 20 * 1024 * 1024)
LOG_TRACE(log, "Revocable bytes after insert one block {}, thread {}", revocable_bytes, thread_num);
if (agg_spill_context->updatePerThreadRevocableMemory(revocable_bytes, thread_num))
{
result.tryMarkNeedSpill();
}
return true;
}
void Aggregator::finishSpill()
{