forked from apache/doris
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvariant_util.cpp
More file actions
2073 lines (1918 loc) · 88.9 KB
/
variant_util.cpp
File metadata and controls
2073 lines (1918 loc) · 88.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include "vec/common/variant_util.h"
#include <assert.h>
#include <fmt/format.h>
#include <gen_cpp/FrontendService.h>
#include <gen_cpp/FrontendService_types.h>
#include <gen_cpp/HeartbeatService_types.h>
#include <gen_cpp/MasterService_types.h>
#include <gen_cpp/Status_types.h>
#include <gen_cpp/Types_types.h>
#include <glog/logging.h>
#include <rapidjson/document.h>
#include <rapidjson/stringbuffer.h>
#include <rapidjson/writer.h>
#include <simdjson/simdjson.h> // IWYU pragma: keep
#include <unicode/uchar.h>
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <list>
#include <memory>
#include <mutex>
#include <optional>
#include <ostream>
#include <set>
#include <stack>
#include <string>
#include <string_view>
#include <unordered_map>
#include <utility>
#include <vector>
#include "common/config.h"
#include "common/status.h"
#include "exprs/json_functions.h"
#include "olap/olap_common.h"
#include "olap/rowset/beta_rowset.h"
#include "olap/rowset/rowset.h"
#include "olap/rowset/rowset_fwd.h"
#include "olap/rowset/segment_v2/variant/variant_column_reader.h"
#include "olap/rowset/segment_v2/variant/variant_column_writer_impl.h"
#include "olap/segment_loader.h"
#include "olap/tablet.h"
#include "olap/tablet_fwd.h"
#include "olap/tablet_schema.h"
#include "re2/re2.h"
#include "runtime/client_cache.h"
#include "runtime/define_primitive_type.h"
#include "runtime/exec_env.h"
#include "runtime/primitive_type.h"
#include "runtime/runtime_state.h"
#include "util/defer_op.h"
#include "vec/columns/column.h"
#include "vec/columns/column_array.h"
#include "vec/columns/column_map.h"
#include "vec/columns/column_nullable.h"
#include "vec/columns/column_string.h"
#include "vec/columns/column_variant.h"
#include "vec/common/assert_cast.h"
#include "vec/common/field_visitors.h"
#include "vec/common/sip_hash.h"
#include "vec/common/typeid_cast.h"
#include "vec/core/block.h"
#include "vec/core/column_numbers.h"
#include "vec/core/column_with_type_and_name.h"
#include "vec/core/field.h"
#include "vec/core/types.h"
#include "vec/data_types/data_type.h"
#include "vec/data_types/data_type_array.h"
#include "vec/data_types/data_type_factory.hpp"
#include "vec/data_types/data_type_jsonb.h"
#include "vec/data_types/data_type_nullable.h"
#include "vec/data_types/data_type_string.h"
#include "vec/data_types/data_type_variant.h"
#include "vec/data_types/get_least_supertype.h"
#include "vec/exprs/function_context.h"
#include "vec/functions/function.h"
#include "vec/functions/simple_function_factory.h"
#include "vec/json/json_parser.h"
#include "vec/json/path_in_data.h"
#include "vec/json/simd_json_parser.h"
namespace doris::vectorized::variant_util {
#include "common/compile_check_begin.h"
inline void append_escaped_regex_char(std::string* regex_output, char ch) {
switch (ch) {
case '.':
case '^':
case '$':
case '+':
case '*':
case '?':
case '(':
case ')':
case '|':
case '{':
case '}':
case '[':
case ']':
case '\\':
regex_output->push_back('\\');
regex_output->push_back(ch);
break;
default:
regex_output->push_back(ch);
break;
}
}
// Small LRU to cap compiled glob patterns
constexpr size_t kGlobRegexCacheCapacity = 256;
struct GlobRegexCacheEntry {
std::shared_ptr<RE2> re2;
std::list<std::string>::iterator lru_it;
};
static std::mutex g_glob_regex_cache_mutex;
static std::list<std::string> g_glob_regex_cache_lru;
static std::unordered_map<std::string, GlobRegexCacheEntry> g_glob_regex_cache;
std::shared_ptr<RE2> get_or_build_re2(const std::string& glob_pattern) {
{
std::lock_guard<std::mutex> lock(g_glob_regex_cache_mutex);
auto it = g_glob_regex_cache.find(glob_pattern);
if (it != g_glob_regex_cache.end()) {
g_glob_regex_cache_lru.splice(g_glob_regex_cache_lru.begin(), g_glob_regex_cache_lru,
it->second.lru_it);
return it->second.re2;
}
}
std::string regex_pattern;
Status st = glob_to_regex(glob_pattern, ®ex_pattern);
if (!st.ok()) {
return nullptr;
}
auto compiled = std::make_shared<RE2>(regex_pattern);
if (!compiled->ok()) {
return nullptr;
}
{
std::lock_guard<std::mutex> lock(g_glob_regex_cache_mutex);
auto it = g_glob_regex_cache.find(glob_pattern);
if (it != g_glob_regex_cache.end()) {
g_glob_regex_cache_lru.splice(g_glob_regex_cache_lru.begin(), g_glob_regex_cache_lru,
it->second.lru_it);
return it->second.re2;
}
g_glob_regex_cache_lru.push_front(glob_pattern);
g_glob_regex_cache.emplace(glob_pattern,
GlobRegexCacheEntry {compiled, g_glob_regex_cache_lru.begin()});
if (g_glob_regex_cache.size() > kGlobRegexCacheCapacity) {
const std::string& evict_key = g_glob_regex_cache_lru.back();
g_glob_regex_cache.erase(evict_key);
g_glob_regex_cache_lru.pop_back();
}
}
return compiled;
}
// Convert a restricted glob pattern into a regex.
// Supported: '*', '?', '[...]', '\\' escape. Others are treated as literals.
Status glob_to_regex(const std::string& glob_pattern, std::string* regex_pattern) {
regex_pattern->clear();
regex_pattern->append("^");
bool is_escaped = false;
size_t pattern_length = glob_pattern.size();
for (size_t index = 0; index < pattern_length; ++index) {
char current_char = glob_pattern[index];
if (is_escaped) {
append_escaped_regex_char(regex_pattern, current_char);
is_escaped = false;
continue;
}
if (current_char == '\\') {
is_escaped = true;
continue;
}
if (current_char == '*') {
regex_pattern->append(".*");
continue;
}
if (current_char == '?') {
regex_pattern->append(".");
continue;
}
if (current_char == '[') {
size_t class_index = index + 1;
bool class_closed = false;
bool is_class_escaped = false;
std::string class_buffer;
if (class_index < pattern_length &&
(glob_pattern[class_index] == '!' || glob_pattern[class_index] == '^')) {
class_buffer.push_back('^');
++class_index;
}
for (; class_index < pattern_length; ++class_index) {
char class_char = glob_pattern[class_index];
if (is_class_escaped) {
class_buffer.push_back(class_char);
is_class_escaped = false;
continue;
}
if (class_char == '\\') {
is_class_escaped = true;
continue;
}
if (class_char == ']') {
class_closed = true;
break;
}
class_buffer.push_back(class_char);
}
if (!class_closed) {
return Status::InvalidArgument("Unclosed character class in glob pattern: {}",
glob_pattern);
}
regex_pattern->append("[");
regex_pattern->append(class_buffer);
regex_pattern->append("]");
index = class_index;
continue;
}
append_escaped_regex_char(regex_pattern, current_char);
}
if (is_escaped) {
append_escaped_regex_char(regex_pattern, '\\');
}
regex_pattern->append("$");
return Status::OK();
}
bool glob_match_re2(const std::string& glob_pattern, const std::string& candidate_path) {
auto compiled = get_or_build_re2(glob_pattern);
if (compiled == nullptr) {
return false;
}
return RE2::FullMatch(candidate_path, *compiled);
}
size_t get_number_of_dimensions(const IDataType& type) {
if (const auto* type_array = typeid_cast<const DataTypeArray*>(&type)) {
return type_array->get_number_of_dimensions();
}
return 0;
}
size_t get_number_of_dimensions(const IColumn& column) {
if (const auto* column_array = check_and_get_column<ColumnArray>(column)) {
return column_array->get_number_of_dimensions();
}
return 0;
}
DataTypePtr get_base_type_of_array(const DataTypePtr& type) {
/// Get raw pointers to avoid extra copying of type pointers.
const DataTypeArray* last_array = nullptr;
const auto* current_type = type.get();
while (const auto* type_array = typeid_cast<const DataTypeArray*>(current_type)) {
current_type = type_array->get_nested_type().get();
last_array = type_array;
}
return last_array ? last_array->get_nested_type() : type;
}
Status cast_column(const ColumnWithTypeAndName& arg, const DataTypePtr& type, ColumnPtr* result) {
ColumnsWithTypeAndName arguments {arg, {nullptr, type, type->get_name()}};
// To prevent from null info lost, we should not call function since the function framework will wrap
// nullable to Variant instead of the root of Variant
// correct output: Nullable(Array(int)) -> Nullable(Variant(Nullable(Array(int))))
// incorrect output: Nullable(Array(int)) -> Nullable(Variant(Array(int)))
if (type->get_primitive_type() == TYPE_VARIANT) {
// If source column is variant, so the nullable info is different from dst column
if (arg.type->get_primitive_type() == TYPE_VARIANT) {
*result = type->is_nullable() ? make_nullable(arg.column) : remove_nullable(arg.column);
return Status::OK();
}
// set variant root column/type to from column/type
CHECK(arg.column->is_nullable());
auto to_type = remove_nullable(type);
const auto& data_type_object = assert_cast<const DataTypeVariant&>(*to_type);
auto variant = ColumnVariant::create(data_type_object.variant_max_subcolumns_count());
variant->create_root(arg.type, arg.column->assume_mutable());
ColumnPtr nullable = ColumnNullable::create(
variant->get_ptr(),
check_and_get_column<ColumnNullable>(arg.column.get())->get_null_map_column_ptr());
*result = type->is_nullable() ? nullable : variant->get_ptr();
return Status::OK();
}
auto function = SimpleFunctionFactory::instance().get_function("CAST", arguments, type);
if (!function) {
return Status::InternalError("Not found cast function {} to {}", arg.type->get_name(),
type->get_name());
}
Block tmp_block {arguments};
uint32_t result_column = cast_set<uint32_t>(tmp_block.columns());
RuntimeState state;
auto ctx = FunctionContext::create_context(&state, {}, {});
if (arg.type->get_primitive_type() == INVALID_TYPE) {
// cast from nothing to any type should result in nulls
*result = type->create_column_const_with_default_value(arg.column->size())
->convert_to_full_column_if_const();
return Status::OK();
}
// We convert column string to jsonb type just add a string jsonb field to dst column instead of parse
// each line in original string column.
ctx->set_string_as_jsonb_string(true);
ctx->set_jsonb_string_as_string(true);
tmp_block.insert({nullptr, type, arg.name});
// TODO(lihangyu): we should handle this error in strict mode
if (!function->execute(ctx.get(), tmp_block, {0}, result_column, arg.column->size())) {
LOG_EVERY_N(WARNING, 100) << fmt::format("cast from {} to {}", arg.type->get_name(),
type->get_name());
*result = type->create_column_const_with_default_value(arg.column->size())
->convert_to_full_column_if_const();
return Status::OK();
}
*result = tmp_block.get_by_position(result_column).column->convert_to_full_column_if_const();
VLOG_DEBUG << fmt::format("{} before convert {}, after convert {}", arg.name,
arg.column->get_name(), (*result)->get_name());
return Status::OK();
}
void get_column_by_type(const vectorized::DataTypePtr& data_type, const std::string& name,
TabletColumn& column, const ExtraInfo& ext_info) {
column.set_name(name);
column.set_type(data_type->get_storage_field_type());
if (ext_info.unique_id >= 0) {
column.set_unique_id(ext_info.unique_id);
}
if (ext_info.parent_unique_id >= 0) {
column.set_parent_unique_id(ext_info.parent_unique_id);
}
if (!ext_info.path_info.empty()) {
column.set_path_info(ext_info.path_info);
}
if (data_type->is_nullable()) {
const auto& real_type = static_cast<const DataTypeNullable&>(*data_type);
column.set_is_nullable(true);
get_column_by_type(real_type.get_nested_type(), name, column, {});
return;
}
if (data_type->get_primitive_type() == PrimitiveType::TYPE_ARRAY) {
TabletColumn child;
get_column_by_type(assert_cast<const DataTypeArray*>(data_type.get())->get_nested_type(),
"", child, {});
column.set_length(TabletColumn::get_field_length_by_type(TPrimitiveType::ARRAY, 0));
column.add_sub_column(child);
return;
}
// size is not fixed when type is string or json
if (is_string_type(data_type->get_primitive_type()) ||
data_type->get_primitive_type() == TYPE_JSONB) {
column.set_length(INT_MAX);
return;
}
PrimitiveType type = data_type->get_primitive_type();
if (is_int_or_bool(type) || is_string_type(type) || is_float_or_double(type) || is_ip(type) ||
is_date_or_datetime(type) || type == PrimitiveType::TYPE_DATEV2) {
column.set_length(cast_set<int32_t>(data_type->get_size_of_value_in_memory()));
return;
}
if (is_decimal(type)) {
column.set_precision(data_type->get_precision());
column.set_frac(data_type->get_scale());
return;
}
// datetimev2 needs scale
if (type == PrimitiveType::TYPE_DATETIMEV2 || type == PrimitiveType::TYPE_TIMESTAMPTZ) {
column.set_precision(-1);
column.set_frac(data_type->get_scale());
return;
}
throw doris::Exception(doris::ErrorCode::INTERNAL_ERROR,
"unexcepted data column type: {}, column name is: {}",
data_type->get_name(), name);
}
TabletColumn get_column_by_type(const vectorized::DataTypePtr& data_type, const std::string& name,
const ExtraInfo& ext_info) {
TabletColumn result;
get_column_by_type(data_type, name, result, ext_info);
return result;
}
// check if two paths which same prefix have different structure
static bool has_different_structure_in_same_path(const PathInData::Parts& lhs,
const PathInData::Parts& rhs) {
if (lhs.size() != rhs.size()) {
return false; // different size means different structure
}
// Since we group by path string, lhs and rhs must have the same size and keys
// We only need to check if they have different nested structure
for (size_t i = 0; i < lhs.size(); ++i) {
if (lhs[i] != rhs[i]) {
VLOG_DEBUG << fmt::format(
"Check different structure: {} vs {}, lhs[i].is_nested: {}, rhs[i].is_nested: "
"{}",
lhs[i].key, rhs[i].key, lhs[i].is_nested, rhs[i].is_nested);
return true;
}
}
return false;
}
Status check_variant_has_no_ambiguous_paths(const PathsInData& tuple_paths) {
// Group paths by their string representation to reduce comparisons
std::unordered_map<std::string, std::vector<size_t>> path_groups;
for (size_t i = 0; i < tuple_paths.size(); ++i) {
// same path should have same structure, so we group them by path
path_groups[tuple_paths[i].get_path()].push_back(i);
// print part of tuple_paths[i]
VLOG_DEBUG << "tuple_paths[i]: " << tuple_paths[i].get_path();
}
// Only compare paths within the same group
for (const auto& [path_str, indices] : path_groups) {
if (indices.size() <= 1) {
continue; // No conflicts possible
}
// Compare all pairs within this group
for (size_t i = 0; i < indices.size(); ++i) {
for (size_t j = 0; j < i; ++j) {
if (has_different_structure_in_same_path(tuple_paths[indices[i]].get_parts(),
tuple_paths[indices[j]].get_parts())) {
return Status::DataQualityError(
"Ambiguous paths: {} vs {} with different nested part {} vs {}",
tuple_paths[indices[i]].get_path(), tuple_paths[indices[j]].get_path(),
tuple_paths[indices[i]].has_nested_part(),
tuple_paths[indices[j]].has_nested_part());
}
}
}
}
return Status::OK();
}
Status update_least_schema_internal(const std::map<PathInData, DataTypes>& subcolumns_types,
TabletSchemaSPtr& common_schema, int32_t variant_col_unique_id,
const std::map<std::string, TabletColumnPtr>& typed_columns,
std::set<PathInData>* path_set) {
PathsInData tuple_paths;
DataTypes tuple_types;
CHECK(common_schema.use_count() == 1);
// Get the least common type for all paths.
for (const auto& [key, subtypes] : subcolumns_types) {
assert(!subtypes.empty());
if (key.get_path() == ColumnVariant::COLUMN_NAME_DUMMY) {
continue;
}
size_t first_dim = get_number_of_dimensions(*subtypes[0]);
tuple_paths.emplace_back(key);
for (size_t i = 1; i < subtypes.size(); ++i) {
if (first_dim != get_number_of_dimensions(*subtypes[i])) {
tuple_types.emplace_back(make_nullable(std::make_shared<DataTypeJsonb>()));
LOG(INFO) << fmt::format(
"Uncompatible types of subcolumn '{}': {} and {}, cast to JSONB",
key.get_path(), subtypes[0]->get_name(), subtypes[i]->get_name());
break;
}
}
if (tuple_paths.size() == tuple_types.size()) {
continue;
}
DataTypePtr common_type;
get_least_supertype_jsonb(subtypes, &common_type);
if (!common_type->is_nullable()) {
common_type = make_nullable(common_type);
}
tuple_types.emplace_back(common_type);
}
CHECK_EQ(tuple_paths.size(), tuple_types.size());
// Append all common type columns of this variant
for (int i = 0; i < tuple_paths.size(); ++i) {
TabletColumn common_column;
// typed path not contains root part
auto path_without_root = tuple_paths[i].copy_pop_front().get_path();
if (typed_columns.contains(path_without_root) && !tuple_paths[i].has_nested_part()) {
common_column = *typed_columns.at(path_without_root);
// parent unique id and path may not be init in write path
common_column.set_parent_unique_id(variant_col_unique_id);
common_column.set_path_info(tuple_paths[i]);
common_column.set_name(tuple_paths[i].get_path());
} else {
// const std::string& column_name = variant_col_name + "." + tuple_paths[i].get_path();
get_column_by_type(tuple_types[i], tuple_paths[i].get_path(), common_column,
ExtraInfo {.unique_id = -1,
.parent_unique_id = variant_col_unique_id,
.path_info = tuple_paths[i]});
}
common_schema->append_column(common_column);
if (path_set != nullptr) {
path_set->insert(tuple_paths[i]);
}
}
return Status::OK();
}
Status update_least_common_schema(const std::vector<TabletSchemaSPtr>& schemas,
TabletSchemaSPtr& common_schema, int32_t variant_col_unique_id,
std::set<PathInData>* path_set) {
std::map<std::string, TabletColumnPtr> typed_columns;
for (const TabletColumnPtr& col :
common_schema->column_by_uid(variant_col_unique_id).get_sub_columns()) {
typed_columns[col->name()] = col;
}
// Types of subcolumns by path from all tuples.
std::map<PathInData, DataTypes> subcolumns_types;
// Collect all paths first to enable batch checking
std::vector<PathInData> all_paths;
for (const TabletSchemaSPtr& schema : schemas) {
for (const TabletColumnPtr& col : schema->columns()) {
// Get subcolumns of this variant
if (col->has_path_info() && col->parent_unique_id() > 0 &&
col->parent_unique_id() == variant_col_unique_id) {
subcolumns_types[*col->path_info_ptr()].emplace_back(
DataTypeFactory::instance().create_data_type(*col, col->is_nullable()));
all_paths.push_back(*col->path_info_ptr());
}
}
}
// Batch check for conflicts
RETURN_IF_ERROR(check_variant_has_no_ambiguous_paths(all_paths));
return update_least_schema_internal(subcolumns_types, common_schema, variant_col_unique_id,
typed_columns, path_set);
}
// Keep variant subcolumn BF support aligned with FE DDL checks.
bool is_bf_supported_by_fe_for_variant_subcolumn(FieldType type) {
switch (type) {
case FieldType::OLAP_FIELD_TYPE_SMALLINT:
case FieldType::OLAP_FIELD_TYPE_INT:
case FieldType::OLAP_FIELD_TYPE_BIGINT:
case FieldType::OLAP_FIELD_TYPE_LARGEINT:
case FieldType::OLAP_FIELD_TYPE_CHAR:
case FieldType::OLAP_FIELD_TYPE_VARCHAR:
case FieldType::OLAP_FIELD_TYPE_STRING:
case FieldType::OLAP_FIELD_TYPE_DATE:
case FieldType::OLAP_FIELD_TYPE_DATETIME:
case FieldType::OLAP_FIELD_TYPE_DATEV2:
case FieldType::OLAP_FIELD_TYPE_DATETIMEV2:
case FieldType::OLAP_FIELD_TYPE_TIMESTAMPTZ:
case FieldType::OLAP_FIELD_TYPE_DECIMAL:
case FieldType::OLAP_FIELD_TYPE_DECIMAL32:
case FieldType::OLAP_FIELD_TYPE_DECIMAL64:
case FieldType::OLAP_FIELD_TYPE_DECIMAL128I:
case FieldType::OLAP_FIELD_TYPE_DECIMAL256:
case FieldType::OLAP_FIELD_TYPE_IPV4:
case FieldType::OLAP_FIELD_TYPE_IPV6:
return true;
default:
return false;
}
}
void inherit_column_attributes(const TabletColumn& source, TabletColumn& target,
TabletSchemaSPtr* target_schema) {
if (!target.is_extracted_column()) {
return;
}
target.set_aggregation_method(source.aggregation());
// 1. bloom filter
if (is_bf_supported_by_fe_for_variant_subcolumn(target.type())) {
target.set_is_bf_column(source.is_bf_column());
}
if (!target_schema) {
return;
}
// 2. inverted index
TabletIndexes indexes_to_add;
auto source_indexes = (*target_schema)->inverted_indexs(source.unique_id());
// if target is variant type, we need to inherit all indexes
// because this schema is a read schema from fe
if (target.is_variant_type()) {
for (auto& index : source_indexes) {
auto index_info = std::make_shared<TabletIndex>(*index);
index_info->set_escaped_escaped_index_suffix_path(target.path_info_ptr()->get_path());
indexes_to_add.emplace_back(std::move(index_info));
}
} else {
inherit_index(source_indexes, indexes_to_add, target);
}
auto target_indexes = (*target_schema)
->inverted_indexs(target.parent_unique_id(),
target.path_info_ptr()->get_path());
if (target_indexes.empty()) {
for (auto& index_info : indexes_to_add) {
(*target_schema)->append_index(std::move(*index_info));
}
}
// 3. TODO: gnragm bf index
}
void inherit_column_attributes(TabletSchemaSPtr& schema) {
// Add index meta if extracted column is missing index meta
for (size_t i = 0; i < schema->num_columns(); ++i) {
TabletColumn& col = schema->mutable_column(i);
if (!col.is_extracted_column()) {
continue;
}
if (schema->field_index(col.parent_unique_id()) == -1) {
// parent column is missing, maybe dropped
continue;
}
inherit_column_attributes(schema->column_by_uid(col.parent_unique_id()), col, &schema);
}
}
Status get_least_common_schema(const std::vector<TabletSchemaSPtr>& schemas,
const TabletSchemaSPtr& base_schema, TabletSchemaSPtr& output_schema,
bool check_schema_size) {
std::vector<int32_t> variant_column_unique_id;
// Construct a schema excluding the extracted columns and gather unique identifiers for variants.
// Ensure that the output schema also excludes these extracted columns. This approach prevents
// duplicated paths following the update_least_common_schema process.
auto build_schema_without_extracted_columns = [&](const TabletSchemaSPtr& base_schema) {
output_schema = std::make_shared<TabletSchema>();
// not copy columns but only shadow copy other attributes
output_schema->shawdow_copy_without_columns(*base_schema);
// Get all columns without extracted columns and collect variant col unique id
for (const TabletColumnPtr& col : base_schema->columns()) {
if (col->is_variant_type()) {
variant_column_unique_id.push_back(col->unique_id());
}
if (!col->is_extracted_column()) {
output_schema->append_column(*col);
}
}
};
if (base_schema == nullptr) {
// Pick tablet schema with max schema version
auto max_version_schema =
*std::max_element(schemas.cbegin(), schemas.cend(),
[](const TabletSchemaSPtr a, const TabletSchemaSPtr b) {
return a->schema_version() < b->schema_version();
});
CHECK(max_version_schema);
build_schema_without_extracted_columns(max_version_schema);
} else {
// use input base_schema schema as base schema
build_schema_without_extracted_columns(base_schema);
}
for (int32_t unique_id : variant_column_unique_id) {
std::set<PathInData> path_set;
RETURN_IF_ERROR(update_least_common_schema(schemas, output_schema, unique_id, &path_set));
}
inherit_column_attributes(output_schema);
if (check_schema_size &&
output_schema->columns().size() > config::variant_max_merged_tablet_schema_size) {
return Status::DataQualityError("Reached max column size limit {}",
config::variant_max_merged_tablet_schema_size);
}
return Status::OK();
}
// sort by paths in lexicographical order
vectorized::ColumnVariant::Subcolumns get_sorted_subcolumns(
const vectorized::ColumnVariant::Subcolumns& subcolumns) {
// sort by paths in lexicographical order
vectorized::ColumnVariant::Subcolumns sorted = subcolumns;
std::sort(sorted.begin(), sorted.end(), [](const auto& lhsItem, const auto& rhsItem) {
return lhsItem->path < rhsItem->path;
});
return sorted;
}
bool has_schema_index_diff(const TabletSchema* new_schema, const TabletSchema* old_schema,
int32_t new_col_idx, int32_t old_col_idx) {
const auto& column_new = new_schema->column(new_col_idx);
const auto& column_old = old_schema->column(old_col_idx);
if (column_new.is_bf_column() != column_old.is_bf_column()) {
return true;
}
auto new_schema_inverted_indexs = new_schema->inverted_indexs(column_new);
auto old_schema_inverted_indexs = old_schema->inverted_indexs(column_old);
if (new_schema_inverted_indexs.size() != old_schema_inverted_indexs.size()) {
return true;
}
for (size_t i = 0; i < new_schema_inverted_indexs.size(); ++i) {
if (!new_schema_inverted_indexs[i]->is_same_except_id(old_schema_inverted_indexs[i])) {
return true;
}
}
return false;
}
TabletColumn create_sparse_column(const TabletColumn& variant) {
TabletColumn res;
res.set_name(variant.name_lower_case() + "." + SPARSE_COLUMN_PATH);
res.set_type(FieldType::OLAP_FIELD_TYPE_MAP);
res.set_aggregation_method(variant.aggregation());
res.set_path_info(PathInData {variant.name_lower_case() + "." + SPARSE_COLUMN_PATH});
res.set_parent_unique_id(variant.unique_id());
// set default value to "NULL" DefaultColumnIterator will call insert_many_defaults
res.set_default_value("NULL");
TabletColumn child_tcolumn;
child_tcolumn.set_type(FieldType::OLAP_FIELD_TYPE_STRING);
res.add_sub_column(child_tcolumn);
res.add_sub_column(child_tcolumn);
return res;
}
TabletColumn create_sparse_shard_column(const TabletColumn& variant, int bucket_index) {
TabletColumn res;
std::string name = variant.name_lower_case() + "." + SPARSE_COLUMN_PATH + ".b" +
std::to_string(bucket_index);
res.set_name(name);
res.set_type(FieldType::OLAP_FIELD_TYPE_MAP);
res.set_aggregation_method(variant.aggregation());
res.set_parent_unique_id(variant.unique_id());
res.set_default_value("NULL");
PathInData path(name);
res.set_path_info(path);
TabletColumn child_tcolumn;
child_tcolumn.set_type(FieldType::OLAP_FIELD_TYPE_STRING);
res.add_sub_column(child_tcolumn);
res.add_sub_column(child_tcolumn);
return res;
}
TabletColumn create_doc_value_column(const TabletColumn& variant, int bucket_index) {
TabletColumn res;
std::string name = variant.name_lower_case() + "." + DOC_VALUE_COLUMN_PATH + ".b" +
std::to_string(bucket_index);
res.set_name(name);
res.set_type(FieldType::OLAP_FIELD_TYPE_MAP);
res.set_aggregation_method(variant.aggregation());
res.set_parent_unique_id(variant.unique_id());
res.set_default_value("NULL");
res.set_path_info(PathInData {name});
TabletColumn child_tcolumn;
child_tcolumn.set_type(FieldType::OLAP_FIELD_TYPE_STRING);
res.add_sub_column(child_tcolumn);
res.add_sub_column(child_tcolumn);
return res;
}
uint32_t variant_binary_shard_of(const StringRef& path, uint32_t bucket_num) {
if (bucket_num <= 1) return 0;
SipHash hash;
hash.update(path.data, path.size);
uint64_t h = hash.get64();
return static_cast<uint32_t>(h % bucket_num);
}
Status VariantCompactionUtil::aggregate_path_to_stats(
const RowsetSharedPtr& rs,
std::unordered_map<int32_t, PathToNoneNullValues>* uid_to_path_stats) {
SegmentCacheHandle segment_cache;
RETURN_IF_ERROR(SegmentLoader::instance()->load_segments(
std::static_pointer_cast<BetaRowset>(rs), &segment_cache));
for (const auto& column : rs->tablet_schema()->columns()) {
if (!column->is_variant_type()) {
continue;
}
for (const auto& segment : segment_cache.get_segments()) {
std::shared_ptr<ColumnReader> column_reader;
OlapReaderStatistics stats;
RETURN_IF_ERROR(
segment->get_column_reader(column->unique_id(), &column_reader, &stats));
if (!column_reader) {
continue;
}
CHECK(column_reader->get_meta_type() == FieldType::OLAP_FIELD_TYPE_VARIANT);
auto* variant_column_reader =
assert_cast<segment_v2::VariantColumnReader*>(column_reader.get());
// load external meta before getting stats
RETURN_IF_ERROR(variant_column_reader->load_external_meta_once());
const auto* source_stats = variant_column_reader->get_stats();
CHECK(source_stats);
// agg path -> stats
for (const auto& [path, size] : source_stats->sparse_column_non_null_size) {
(*uid_to_path_stats)[column->unique_id()][path] += size;
}
for (const auto& [path, size] : source_stats->subcolumns_non_null_size) {
(*uid_to_path_stats)[column->unique_id()][path] += size;
}
}
}
return Status::OK();
}
Status VariantCompactionUtil::aggregate_variant_extended_info(
const RowsetSharedPtr& rs,
std::unordered_map<int32_t, VariantExtendedInfo>* uid_to_variant_extended_info) {
SegmentCacheHandle segment_cache;
RETURN_IF_ERROR(SegmentLoader::instance()->load_segments(
std::static_pointer_cast<BetaRowset>(rs), &segment_cache));
for (const auto& column : rs->tablet_schema()->columns()) {
if (!column->is_variant_type()) {
continue;
}
for (const auto& segment : segment_cache.get_segments()) {
std::shared_ptr<ColumnReader> column_reader;
OlapReaderStatistics stats;
RETURN_IF_ERROR(
segment->get_column_reader(column->unique_id(), &column_reader, &stats));
if (!column_reader) {
continue;
}
CHECK(column_reader->get_meta_type() == FieldType::OLAP_FIELD_TYPE_VARIANT);
auto* variant_column_reader =
assert_cast<segment_v2::VariantColumnReader*>(column_reader.get());
// load external meta before getting stats
RETURN_IF_ERROR(variant_column_reader->load_external_meta_once());
const auto* source_stats = variant_column_reader->get_stats();
CHECK(source_stats);
// 1. agg path -> stats
for (const auto& [path, size] : source_stats->sparse_column_non_null_size) {
(*uid_to_variant_extended_info)[column->unique_id()]
.path_to_none_null_values[path] += size;
(*uid_to_variant_extended_info)[column->unique_id()].sparse_paths.emplace(path);
}
for (const auto& [path, size] : source_stats->subcolumns_non_null_size) {
(*uid_to_variant_extended_info)[column->unique_id()]
.path_to_none_null_values[path] += size;
}
//2. agg path -> schema
auto& paths_types =
(*uid_to_variant_extended_info)[column->unique_id()].path_to_data_types;
variant_column_reader->get_subcolumns_types(&paths_types);
// 3. extract typed paths
auto& typed_paths = (*uid_to_variant_extended_info)[column->unique_id()].typed_paths;
variant_column_reader->get_typed_paths(&typed_paths);
// 4. extract nested paths
auto& nested_paths = (*uid_to_variant_extended_info)[column->unique_id()].nested_paths;
variant_column_reader->get_nested_paths(&nested_paths);
}
}
return Status::OK();
}
// get the subpaths and sparse paths for the variant column
void VariantCompactionUtil::get_subpaths(int32_t max_subcolumns_count,
const PathToNoneNullValues& stats,
TabletSchema::PathsSetInfo& paths_set_info) {
// max_subcolumns_count is 0 means no limit
if (max_subcolumns_count > 0 && stats.size() > max_subcolumns_count) {
std::vector<std::pair<size_t, std::string_view>> paths_with_sizes;
paths_with_sizes.reserve(stats.size());
for (const auto& [path, size] : stats) {
paths_with_sizes.emplace_back(size, path);
}
std::sort(paths_with_sizes.begin(), paths_with_sizes.end(), std::greater());
// Select top N paths as subcolumns, remaining paths as sparse columns
for (const auto& [size, path] : paths_with_sizes) {
if (paths_set_info.sub_path_set.size() < max_subcolumns_count) {
paths_set_info.sub_path_set.emplace(path);
} else {
paths_set_info.sparse_path_set.emplace(path);
}
}
LOG(INFO) << "subpaths " << paths_set_info.sub_path_set.size() << " sparse paths "
<< paths_set_info.sparse_path_set.size() << " variant max subcolumns count "
<< max_subcolumns_count << " stats size " << paths_with_sizes.size();
} else {
// Apply all paths as subcolumns
for (const auto& [path, _] : stats) {
paths_set_info.sub_path_set.emplace(path);
}
}
}
Status VariantCompactionUtil::check_path_stats(const std::vector<RowsetSharedPtr>& intputs,
RowsetSharedPtr output, BaseTabletSPtr tablet) {
if (output->tablet_schema()->num_variant_columns() == 0) {
return Status::OK();
}
// check no extended schema in input rowsets
for (const auto& rowset : intputs) {
for (const auto& column : rowset->tablet_schema()->columns()) {
if (column->is_extracted_column()) {
return Status::OK();
}
}
}
// check no extended schema in output rowset
for (const auto& column : output->tablet_schema()->columns()) {
if (column->is_extracted_column()) {
return Status::InternalError("Unexpected extracted column {} in output rowset",
column->name());
}
}
// only check path stats for dup_keys since the rows may be merged in other models
if (tablet->keys_type() != KeysType::DUP_KEYS) {
return Status::OK();
}
// if there is a delete predicate in the input rowsets, we skip the path stats check
for (auto& rowset : intputs) {
if (rowset->rowset_meta()->has_delete_predicate()) {
return Status::OK();
}
}
std::unordered_map<int32_t, PathToNoneNullValues> original_uid_to_path_stats;
for (const auto& rs : intputs) {
RETURN_IF_ERROR(aggregate_path_to_stats(rs, &original_uid_to_path_stats));
}
std::unordered_map<int32_t, PathToNoneNullValues> output_uid_to_path_stats;
RETURN_IF_ERROR(aggregate_path_to_stats(output, &output_uid_to_path_stats));
for (const auto& [uid, stats] : output_uid_to_path_stats) {
if (output->tablet_schema()->column_by_uid(uid).is_variant_type() &&
output->tablet_schema()->column_by_uid(uid).variant_enable_doc_mode()) {
continue;
}
if (original_uid_to_path_stats.find(uid) == original_uid_to_path_stats.end()) {
return Status::InternalError("Path stats not found for uid {}, tablet_id {}", uid,
tablet->tablet_id());
}
// In input rowsets, some rowsets may have statistics values exceeding the maximum limit,
// which leads to inaccurate statistics
if (stats.size() > output->tablet_schema()
->column_by_uid(uid)
.variant_max_sparse_column_statistics_size()) {
// When there is only one segment, we can ensure that the size of each path in output stats is accurate
if (output->num_segments() == 1) {
for (const auto& [path, size] : stats) {
if (original_uid_to_path_stats.at(uid).find(path) ==
original_uid_to_path_stats.at(uid).end()) {
continue;
}
if (original_uid_to_path_stats.at(uid).at(path) > size) {
return Status::InternalError(
"Path stats not smaller for uid {} with path `{}`, input size {}, "
"output "
"size {}, "
"tablet_id {}",
uid, path, original_uid_to_path_stats.at(uid).at(path), size,
tablet->tablet_id());
}
}
}
}
// in this case, input stats is accurate, so we check the stats size and stats value
else {
for (const auto& [path, size] : stats) {
if (original_uid_to_path_stats.at(uid).find(path) ==
original_uid_to_path_stats.at(uid).end()) {
return Status::InternalError(
"Path stats not found for uid {}, path {}, tablet_id {}", uid, path,