Coverage Report

Created: 2026-05-14 03:59

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/exec/common/variant_util.cpp
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "exec/common/variant_util.h"
19
20
#include <assert.h>
21
#include <fmt/format.h>
22
#include <gen_cpp/FrontendService.h>
23
#include <gen_cpp/FrontendService_types.h>
24
#include <gen_cpp/HeartbeatService_types.h>
25
#include <gen_cpp/MasterService_types.h>
26
#include <gen_cpp/Status_types.h>
27
#include <gen_cpp/Types_types.h>
28
#include <glog/logging.h>
29
#include <rapidjson/document.h>
30
#include <rapidjson/stringbuffer.h>
31
#include <rapidjson/writer.h>
32
#include <simdjson/simdjson.h> // IWYU pragma: keep
33
#include <unicode/uchar.h>
34
35
#include <algorithm>
36
#include <cassert>
37
#include <cstddef>
38
#include <cstdint>
39
#include <cstring>
40
#include <list>
41
#include <memory>
42
#include <mutex>
43
#include <optional>
44
#include <ostream>
45
#include <ranges>
46
#include <set>
47
#include <stack>
48
#include <string>
49
#include <string_view>
50
#include <unordered_map>
51
#include <utility>
52
#include <vector>
53
54
#include "common/config.h"
55
#include "common/status.h"
56
#include "core/assert_cast.h"
57
#include "core/block/block.h"
58
#include "core/block/column_numbers.h"
59
#include "core/block/column_with_type_and_name.h"
60
#include "core/column/column.h"
61
#include "core/column/column_array.h"
62
#include "core/column/column_map.h"
63
#include "core/column/column_nullable.h"
64
#include "core/column/column_string.h"
65
#include "core/column/column_variant.h"
66
#include "core/data_type/data_type.h"
67
#include "core/data_type/data_type_array.h"
68
#include "core/data_type/data_type_factory.hpp"
69
#include "core/data_type/data_type_jsonb.h"
70
#include "core/data_type/data_type_nullable.h"
71
#include "core/data_type/data_type_string.h"
72
#include "core/data_type/data_type_variant.h"
73
#include "core/data_type/define_primitive_type.h"
74
#include "core/data_type/get_least_supertype.h"
75
#include "core/data_type/primitive_type.h"
76
#include "core/field.h"
77
#include "core/typeid_cast.h"
78
#include "core/types.h"
79
#include "exec/common/field_visitors.h"
80
#include "exec/common/sip_hash.h"
81
#include "exprs/function/function.h"
82
#include "exprs/function/simple_function_factory.h"
83
#include "exprs/function_context.h"
84
#include "exprs/json_functions.h"
85
#include "re2/re2.h"
86
#include "runtime/exec_env.h"
87
#include "runtime/runtime_state.h"
88
#include "storage/olap_common.h"
89
#include "storage/rowset/beta_rowset.h"
90
#include "storage/rowset/rowset.h"
91
#include "storage/rowset/rowset_fwd.h"
92
#include "storage/segment/segment_loader.h"
93
#include "storage/segment/variant/nested_group_path.h"
94
#include "storage/segment/variant/variant_column_reader.h"
95
#include "storage/segment/variant/variant_column_writer_impl.h"
96
#include "storage/tablet/tablet.h"
97
#include "storage/tablet/tablet_fwd.h"
98
#include "storage/tablet/tablet_schema.h"
99
#include "util/client_cache.h"
100
#include "util/defer_op.h"
101
#include "util/json/json_parser.h"
102
#include "util/json/path_in_data.h"
103
#include "util/json/simd_json_parser.h"
104
105
namespace doris::variant_util {
106
107
2.76k
inline void append_escaped_regex_char(std::string* regex_output, char ch) {
108
2.76k
    switch (ch) {
109
22
    case '.':
110
24
    case '^':
111
26
    case '$':
112
28
    case '+':
113
34
    case '*':
114
36
    case '?':
115
38
    case '(':
116
40
    case ')':
117
42
    case '|':
118
44
    case '{':
119
46
    case '}':
120
48
    case '[':
121
48
    case ']':
122
52
    case '\\':
123
52
        regex_output->push_back('\\');
124
52
        regex_output->push_back(ch);
125
52
        break;
126
2.71k
    default:
127
2.71k
        regex_output->push_back(ch);
128
2.71k
        break;
129
2.76k
    }
130
2.76k
}
131
132
// Small LRU to cap compiled glob patterns
133
constexpr size_t kGlobRegexCacheCapacity = 256;
134
135
struct GlobRegexCacheEntry {
136
    std::shared_ptr<RE2> re2;
137
    std::list<std::string>::iterator lru_it;
138
};
139
140
static std::mutex g_glob_regex_cache_mutex;
141
static std::list<std::string> g_glob_regex_cache_lru;
142
static std::unordered_map<std::string, GlobRegexCacheEntry> g_glob_regex_cache;
143
144
161k
std::shared_ptr<RE2> get_or_build_re2(const std::string& glob_pattern) {
145
161k
    {
146
161k
        std::lock_guard<std::mutex> lock(g_glob_regex_cache_mutex);
147
161k
        auto it = g_glob_regex_cache.find(glob_pattern);
148
161k
        if (it != g_glob_regex_cache.end()) {
149
160k
            g_glob_regex_cache_lru.splice(g_glob_regex_cache_lru.begin(), g_glob_regex_cache_lru,
150
160k
                                          it->second.lru_it);
151
160k
            return it->second.re2;
152
160k
        }
153
161k
    }
154
221
    std::string regex_pattern;
155
221
    Status st = glob_to_regex(glob_pattern, &regex_pattern);
156
221
    if (!st.ok()) {
157
2
        return nullptr;
158
2
    }
159
219
    auto compiled = std::make_shared<RE2>(regex_pattern);
160
219
    if (!compiled->ok()) {
161
3
        return nullptr;
162
3
    }
163
216
    {
164
216
        std::lock_guard<std::mutex> lock(g_glob_regex_cache_mutex);
165
216
        auto it = g_glob_regex_cache.find(glob_pattern);
166
216
        if (it != g_glob_regex_cache.end()) {
167
0
            g_glob_regex_cache_lru.splice(g_glob_regex_cache_lru.begin(), g_glob_regex_cache_lru,
168
0
                                          it->second.lru_it);
169
0
            return it->second.re2;
170
0
        }
171
216
        g_glob_regex_cache_lru.push_front(glob_pattern);
172
216
        g_glob_regex_cache.emplace(glob_pattern,
173
216
                                   GlobRegexCacheEntry {compiled, g_glob_regex_cache_lru.begin()});
174
216
        if (g_glob_regex_cache.size() > kGlobRegexCacheCapacity) {
175
0
            const std::string& evict_key = g_glob_regex_cache_lru.back();
176
0
            g_glob_regex_cache.erase(evict_key);
177
0
            g_glob_regex_cache_lru.pop_back();
178
0
        }
179
216
    }
180
0
    return compiled;
181
216
}
182
183
// Convert a restricted glob pattern into a regex.
184
// Supported: '*', '?', '[...]', '\\' escape. Others are treated as literals.
185
289
Status glob_to_regex(const std::string& glob_pattern, std::string* regex_pattern) {
186
289
    regex_pattern->clear();
187
289
    regex_pattern->append("^");
188
289
    bool is_escaped = false;
189
289
    size_t pattern_length = glob_pattern.size();
190
3.18k
    for (size_t index = 0; index < pattern_length; ++index) {
191
2.89k
        char current_char = glob_pattern[index];
192
2.89k
        if (is_escaped) {
193
10
            append_escaped_regex_char(regex_pattern, current_char);
194
10
            is_escaped = false;
195
10
            continue;
196
10
        }
197
2.88k
        if (current_char == '\\') {
198
14
            is_escaped = true;
199
14
            continue;
200
14
        }
201
2.87k
        if (current_char == '*') {
202
71
            regex_pattern->append(".*");
203
71
            continue;
204
71
        }
205
2.80k
        if (current_char == '?') {
206
15
            regex_pattern->append(".");
207
15
            continue;
208
15
        }
209
2.78k
        if (current_char == '[') {
210
33
            size_t class_index = index + 1;
211
33
            bool class_closed = false;
212
33
            bool is_class_escaped = false;
213
33
            std::string class_buffer;
214
33
            if (class_index < pattern_length &&
215
33
                (glob_pattern[class_index] == '!' || glob_pattern[class_index] == '^')) {
216
9
                class_buffer.push_back('^');
217
9
                ++class_index;
218
9
            }
219
99
            for (; class_index < pattern_length; ++class_index) {
220
95
                char class_char = glob_pattern[class_index];
221
95
                if (is_class_escaped) {
222
10
                    class_buffer.push_back(class_char);
223
10
                    is_class_escaped = false;
224
10
                    continue;
225
10
                }
226
85
                if (class_char == '\\') {
227
10
                    is_class_escaped = true;
228
10
                    continue;
229
10
                }
230
75
                if (class_char == ']') {
231
29
                    class_closed = true;
232
29
                    break;
233
29
                }
234
46
                class_buffer.push_back(class_char);
235
46
            }
236
33
            if (!class_closed) {
237
4
                return Status::InvalidArgument("Unclosed character class in glob pattern: {}",
238
4
                                               glob_pattern);
239
4
            }
240
29
            regex_pattern->append("[");
241
29
            regex_pattern->append(class_buffer);
242
29
            regex_pattern->append("]");
243
29
            index = class_index;
244
29
            continue;
245
33
        }
246
2.75k
        append_escaped_regex_char(regex_pattern, current_char);
247
2.75k
    }
248
285
    if (is_escaped) {
249
4
        append_escaped_regex_char(regex_pattern, '\\');
250
4
    }
251
285
    regex_pattern->append("$");
252
285
    return Status::OK();
253
289
}
254
255
161k
bool glob_match_re2(const std::string& glob_pattern, const std::string& candidate_path) {
256
161k
    auto compiled = get_or_build_re2(glob_pattern);
257
161k
    if (compiled == nullptr) {
258
5
        return false;
259
5
    }
260
161k
    return RE2::FullMatch(candidate_path, *compiled);
261
161k
}
262
263
// NestedGroup's physical children and offsets are produced by NestedGroupWriteProvider, not by
264
// appending TabletSchema extracted columns here. This predicate keeps only ordinary Variant paths
265
// that are outside the NG tree, for example `v.owner` beside `v.items[*]`.
266
0
bool is_regular_path_outside_nested_group(const PathInData& path) {
267
0
    const std::string& relative_path = path.get_path();
268
0
    return !relative_path.empty() && !path.get_is_typed() && !path.has_nested_part() &&
269
0
           !segment_v2::contains_nested_group_marker(relative_path) &&
270
0
           !segment_v2::is_root_nested_group_path(relative_path) &&
271
0
           relative_path != SPARSE_COLUMN_PATH &&
272
0
           relative_path.find(DOC_VALUE_COLUMN_PATH) == std::string::npos;
273
0
}
274
275
bool should_materialize_nested_group_regular_subcolumns(
276
        const TabletColumnPtr& column,
277
787
        const std::unordered_map<int32_t, VariantExtendedInfo>& uid_to_variant_extended_info) {
278
787
    const auto info_it = uid_to_variant_extended_info.find(column->unique_id());
279
787
    return column->variant_enable_nested_group() ||
280
787
           (info_it != uid_to_variant_extended_info.end() && info_it->second.has_nested_group);
281
787
}
282
283
std::unordered_set<int32_t> collect_nested_group_compaction_root_uids(
284
        const TabletSchemaSPtr& target,
285
8.13k
        const std::unordered_map<int32_t, VariantExtendedInfo>& uid_to_variant_extended_info) {
286
8.13k
    std::unordered_set<int32_t> root_uids;
287
92.0k
    for (const TabletColumnPtr& column : target->columns()) {
288
92.0k
        if (column->is_variant_type() && should_materialize_nested_group_regular_subcolumns(
289
789
                                                 column, uid_to_variant_extended_info)) {
290
1
            root_uids.insert(column->unique_id());
291
1
        }
292
92.0k
    }
293
8.13k
    return root_uids;
294
8.13k
}
295
296
PathToDataTypes collect_regular_types_outside_nested_group(
297
1
        const VariantExtendedInfo& extended_info) {
298
1
    PathToDataTypes regular_path_to_data_types;
299
1
    for (const auto& [path, data_types] : extended_info.path_to_data_types) {
300
0
        if (!is_regular_path_outside_nested_group(path)) {
301
0
            continue;
302
0
        }
303
0
        regular_path_to_data_types.emplace(path, data_types);
304
0
    }
305
1
    return regular_path_to_data_types;
306
1
}
307
308
957
size_t get_number_of_dimensions(const IDataType& type) {
309
957
    if (const auto* type_array = typeid_cast<const DataTypeArray*>(&type)) {
310
4
        return type_array->get_number_of_dimensions();
311
4
    }
312
953
    return 0;
313
957
}
314
3
size_t get_number_of_dimensions(const IColumn& column) {
315
3
    if (const auto* column_array = check_and_get_column<ColumnArray>(column)) {
316
2
        return column_array->get_number_of_dimensions();
317
2
    }
318
1
    return 0;
319
3
}
320
321
131k
DataTypePtr get_base_type_of_array(const DataTypePtr& type) {
322
    /// Get raw pointers to avoid extra copying of type pointers.
323
131k
    const DataTypeArray* last_array = nullptr;
324
131k
    const auto* current_type = type.get();
325
131k
    if (const auto* nullable = typeid_cast<const DataTypeNullable*>(current_type)) {
326
131k
        current_type = nullable->get_nested_type().get();
327
131k
    }
328
133k
    while (const auto* type_array = typeid_cast<const DataTypeArray*>(current_type)) {
329
1.21k
        current_type = type_array->get_nested_type().get();
330
1.21k
        last_array = type_array;
331
1.21k
        if (const auto* nullable = typeid_cast<const DataTypeNullable*>(current_type)) {
332
1.21k
            current_type = nullable->get_nested_type().get();
333
1.21k
        }
334
1.21k
    }
335
131k
    return last_array ? last_array->get_nested_type() : type;
336
131k
}
337
338
71.8k
Status cast_column(const ColumnWithTypeAndName& arg, const DataTypePtr& type, ColumnPtr* result) {
339
71.8k
    ColumnsWithTypeAndName arguments {arg, {nullptr, type, type->get_name()}};
340
341
    // To prevent from null info lost, we should not call function since the function framework will wrap
342
    // nullable to Variant instead of the root of Variant
343
    // correct output: Nullable(Array(int)) -> Nullable(Variant(Nullable(Array(int))))
344
    // incorrect output: Nullable(Array(int)) -> Nullable(Variant(Array(int)))
345
71.8k
    if (type->get_primitive_type() == TYPE_VARIANT) {
346
        // If source column is variant, so the nullable info is different from dst column
347
13.0k
        if (arg.type->get_primitive_type() == TYPE_VARIANT) {
348
492
            *result = type->is_nullable() ? make_nullable(arg.column) : remove_nullable(arg.column);
349
492
            return Status::OK();
350
492
        }
351
        // set variant root column/type to from column/type
352
13.0k
        CHECK(arg.column->is_nullable());
353
12.5k
        auto to_type = remove_nullable(type);
354
12.5k
        const auto& data_type_object = assert_cast<const DataTypeVariant&>(*to_type);
355
12.5k
        auto variant = ColumnVariant::create(data_type_object.variant_max_subcolumns_count(),
356
12.5k
                                             data_type_object.enable_doc_mode());
357
358
12.5k
        variant->create_root(arg.type, arg.column->assume_mutable());
359
12.5k
        ColumnPtr nullable = ColumnNullable::create(
360
12.5k
                variant->get_ptr(),
361
12.5k
                check_and_get_column<ColumnNullable>(arg.column.get())->get_null_map_column_ptr());
362
12.5k
        *result = type->is_nullable() ? nullable : variant->get_ptr();
363
12.5k
        return Status::OK();
364
13.0k
    }
365
366
58.8k
    auto function = SimpleFunctionFactory::instance().get_function("CAST", arguments, type);
367
58.8k
    if (!function) {
368
0
        return Status::InternalError("Not found cast function {} to {}", arg.type->get_name(),
369
0
                                     type->get_name());
370
0
    }
371
58.8k
    Block tmp_block {arguments};
372
58.8k
    uint32_t result_column = cast_set<uint32_t>(tmp_block.columns());
373
58.8k
    RuntimeState state;
374
58.8k
    auto ctx = FunctionContext::create_context(&state, {}, {});
375
376
58.8k
    if (arg.type->get_primitive_type() == INVALID_TYPE) {
377
        // cast from nothing to any type should result in nulls
378
6.05k
        *result = type->create_column_const_with_default_value(arg.column->size())
379
6.05k
                          ->convert_to_full_column_if_const();
380
6.05k
        return Status::OK();
381
6.05k
    }
382
383
    // We convert column string to jsonb type just add a string jsonb field to dst column instead of parse
384
    // each line in original string column.
385
52.8k
    ctx->set_string_as_jsonb_string(true);
386
52.8k
    ctx->set_jsonb_string_as_string(true);
387
52.8k
    tmp_block.insert({nullptr, type, arg.name});
388
    // TODO(lihangyu): we should handle this error in strict mode
389
52.8k
    if (!function->execute(ctx.get(), tmp_block, {0}, result_column, arg.column->size())) {
390
1
        LOG_EVERY_N(WARNING, 100) << fmt::format("cast from {} to {}", arg.type->get_name(),
391
1
                                                 type->get_name());
392
1
        *result = type->create_column_const_with_default_value(arg.column->size())
393
1
                          ->convert_to_full_column_if_const();
394
1
        return Status::OK();
395
1
    }
396
52.8k
    *result = tmp_block.get_by_position(result_column).column->convert_to_full_column_if_const();
397
52.8k
    VLOG_DEBUG << fmt::format("{} before convert {}, after convert {}", arg.name,
398
8
                              arg.column->get_name(), (*result)->get_name());
399
52.8k
    return Status::OK();
400
52.8k
}
401
402
void get_column_by_type(const DataTypePtr& data_type, const std::string& name, TabletColumn& column,
403
266k
                        const ExtraInfo& ext_info) {
404
266k
    column.set_name(name);
405
266k
    column.set_type(data_type->get_storage_field_type());
406
266k
    if (ext_info.unique_id >= 0) {
407
4
        column.set_unique_id(ext_info.unique_id);
408
4
    }
409
266k
    if (ext_info.parent_unique_id >= 0) {
410
131k
        column.set_parent_unique_id(ext_info.parent_unique_id);
411
131k
    }
412
266k
    if (!ext_info.path_info.empty()) {
413
131k
        column.set_path_info(ext_info.path_info);
414
131k
    }
415
266k
    if (data_type->is_nullable()) {
416
133k
        const auto& real_type = static_cast<const DataTypeNullable&>(*data_type);
417
133k
        column.set_is_nullable(true);
418
133k
        get_column_by_type(real_type.get_nested_type(), name, column, {});
419
133k
        return;
420
133k
    }
421
133k
    if (data_type->get_primitive_type() == PrimitiveType::TYPE_ARRAY) {
422
1.20k
        TabletColumn child;
423
1.20k
        get_column_by_type(assert_cast<const DataTypeArray*>(data_type.get())->get_nested_type(),
424
1.20k
                           "", child, {});
425
1.20k
        column.set_length(TabletColumn::get_field_length_by_type(TPrimitiveType::ARRAY, 0));
426
1.20k
        column.add_sub_column(child);
427
1.20k
        return;
428
1.20k
    }
429
131k
    if (data_type->get_primitive_type() == PrimitiveType::TYPE_VARIANT) {
430
0
        const auto* dt_variant = assert_cast<const DataTypeVariant*>(data_type.get());
431
0
        column.set_variant_max_subcolumns_count(dt_variant->variant_max_subcolumns_count());
432
0
        column.set_variant_enable_doc_mode(dt_variant->enable_doc_mode());
433
0
        return;
434
0
    }
435
    // size is not fixed when type is string or json
436
131k
    if (is_string_type(data_type->get_primitive_type()) ||
437
131k
        data_type->get_primitive_type() == TYPE_JSONB) {
438
20.3k
        column.set_length(INT_MAX);
439
20.3k
        return;
440
20.3k
    }
441
442
111k
    PrimitiveType type = data_type->get_primitive_type();
443
111k
    if (is_int_or_bool(type) || is_string_type(type) || is_float_or_double(type) || is_ip(type) ||
444
111k
        is_date_or_datetime(type) || type == PrimitiveType::TYPE_DATEV2) {
445
111k
        column.set_length(cast_set<int32_t>(data_type->get_size_of_value_in_memory()));
446
111k
        return;
447
111k
    }
448
107
    if (is_decimal(type)) {
449
105
        column.set_precision(data_type->get_precision());
450
105
        column.set_frac(data_type->get_scale());
451
105
        return;
452
105
    }
453
    // datetimev2 needs scale
454
17
    if (type == PrimitiveType::TYPE_DATETIMEV2 || type == PrimitiveType::TYPE_TIMESTAMPTZ) {
455
17
        column.set_precision(-1);
456
17
        column.set_frac(data_type->get_scale());
457
17
        return;
458
17
    }
459
460
18.4E
    throw doris::Exception(doris::ErrorCode::INTERNAL_ERROR,
461
18.4E
                           "unexcepted data column type: {}, column name is: {}",
462
18.4E
                           data_type->get_name(), name);
463
2
}
464
465
TabletColumn get_column_by_type(const DataTypePtr& data_type, const std::string& name,
466
130k
                                const ExtraInfo& ext_info) {
467
130k
    TabletColumn result;
468
130k
    get_column_by_type(data_type, name, result, ext_info);
469
130k
    return result;
470
130k
}
471
472
// check if two paths which same prefix have different structure
473
static bool has_different_structure_in_same_path(const PathInData::Parts& lhs,
474
9.04k
                                                 const PathInData::Parts& rhs) {
475
9.04k
    if (lhs.size() != rhs.size()) {
476
1
        return false; // different size means different structure
477
1
    }
478
    // Since we group by path string, lhs and rhs must have the same size and keys
479
    // We only need to check if they have different nested structure
480
36.1k
    for (size_t i = 0; i < lhs.size(); ++i) {
481
27.0k
        if (lhs[i] != rhs[i]) {
482
5
            VLOG_DEBUG << fmt::format(
483
0
                    "Check different structure: {} vs {}, lhs[i].is_nested: {}, rhs[i].is_nested: "
484
0
                    "{}",
485
0
                    lhs[i].key, rhs[i].key, lhs[i].is_nested, rhs[i].is_nested);
486
5
            return true;
487
5
        }
488
27.0k
    }
489
9.03k
    return false;
490
9.04k
}
491
492
4.81k
Status check_variant_has_no_ambiguous_paths(const PathsInData& tuple_paths) {
493
    // Group paths by their string representation to reduce comparisons
494
4.81k
    std::unordered_map<std::string, std::vector<size_t>> path_groups;
495
496
26.8k
    for (size_t i = 0; i < tuple_paths.size(); ++i) {
497
        // same path should have same structure, so we group them by path
498
22.0k
        path_groups[tuple_paths[i].get_path()].push_back(i);
499
        // print part of tuple_paths[i]
500
22.0k
        VLOG_DEBUG << "tuple_paths[i]: " << tuple_paths[i].get_path();
501
22.0k
    }
502
503
    // Only compare paths within the same group
504
13.0k
    for (const auto& [path_str, indices] : path_groups) {
505
13.0k
        if (indices.size() <= 1) {
506
3.99k
            continue; // No conflicts possible
507
3.99k
        }
508
509
        // Compare all pairs within this group
510
27.0k
        for (size_t i = 0; i < indices.size(); ++i) {
511
27.0k
            for (size_t j = 0; j < i; ++j) {
512
9.04k
                if (has_different_structure_in_same_path(tuple_paths[indices[i]].get_parts(),
513
9.04k
                                                         tuple_paths[indices[j]].get_parts())) {
514
5
                    return Status::DataQualityError(
515
5
                            "Ambiguous paths: {} vs {} with different nested part {} vs {}",
516
5
                            tuple_paths[indices[i]].get_path(), tuple_paths[indices[j]].get_path(),
517
5
                            tuple_paths[indices[i]].has_nested_part(),
518
5
                            tuple_paths[indices[j]].has_nested_part());
519
5
                }
520
9.04k
            }
521
18.0k
        }
522
9.01k
    }
523
4.81k
    return Status::OK();
524
4.81k
}
525
526
Status update_least_schema_internal(const std::map<PathInData, DataTypes>& subcolumns_types,
527
                                    TabletSchemaSPtr& common_schema, int32_t variant_col_unique_id,
528
                                    const std::map<std::string, TabletColumnPtr>& typed_columns,
529
1.77k
                                    std::set<PathInData>* path_set) {
530
1.77k
    PathsInData tuple_paths;
531
1.77k
    DataTypes tuple_types;
532
1.77k
    CHECK(common_schema.use_count() == 1);
533
    // Get the least common type for all paths.
534
1.77k
    for (const auto& [key, subtypes] : subcolumns_types) {
535
923
        assert(!subtypes.empty());
536
923
        if (key.get_path() == ColumnVariant::COLUMN_NAME_DUMMY) {
537
0
            continue;
538
0
        }
539
923
        size_t first_dim = get_number_of_dimensions(*subtypes[0]);
540
923
        tuple_paths.emplace_back(key);
541
953
        for (size_t i = 1; i < subtypes.size(); ++i) {
542
31
            if (first_dim != get_number_of_dimensions(*subtypes[i])) {
543
1
                tuple_types.emplace_back(make_nullable(std::make_shared<DataTypeJsonb>()));
544
1
                LOG(INFO) << fmt::format(
545
1
                        "Uncompatible types of subcolumn '{}': {} and {}, cast to JSONB",
546
1
                        key.get_path(), subtypes[0]->get_name(), subtypes[i]->get_name());
547
1
                break;
548
1
            }
549
31
        }
550
923
        if (tuple_paths.size() == tuple_types.size()) {
551
1
            continue;
552
1
        }
553
922
        DataTypePtr common_type;
554
922
        get_least_supertype_jsonb(subtypes, &common_type);
555
922
        if (!common_type->is_nullable()) {
556
3
            common_type = make_nullable(common_type);
557
3
        }
558
922
        tuple_types.emplace_back(common_type);
559
922
    }
560
1.77k
    CHECK_EQ(tuple_paths.size(), tuple_types.size());
561
562
    // Append all common type columns of this variant
563
2.70k
    for (int i = 0; i < tuple_paths.size(); ++i) {
564
923
        TabletColumn common_column;
565
        // typed path not contains root part
566
923
        auto path_without_root = tuple_paths[i].copy_pop_front().get_path();
567
923
        if (typed_columns.contains(path_without_root) && !tuple_paths[i].has_nested_part()) {
568
0
            common_column = *typed_columns.at(path_without_root);
569
            // parent unique id and path may not be init in write path
570
0
            common_column.set_parent_unique_id(variant_col_unique_id);
571
0
            common_column.set_path_info(tuple_paths[i]);
572
0
            common_column.set_name(tuple_paths[i].get_path());
573
923
        } else {
574
            // const std::string& column_name = variant_col_name + "." + tuple_paths[i].get_path();
575
923
            get_column_by_type(tuple_types[i], tuple_paths[i].get_path(), common_column,
576
923
                               ExtraInfo {.unique_id = -1,
577
923
                                          .parent_unique_id = variant_col_unique_id,
578
923
                                          .path_info = tuple_paths[i]});
579
923
        }
580
923
        common_schema->append_column(common_column);
581
923
        if (path_set != nullptr) {
582
920
            path_set->insert(tuple_paths[i]);
583
920
        }
584
923
    }
585
1.77k
    return Status::OK();
586
1.77k
}
587
588
Status update_least_common_schema(const std::vector<TabletSchemaSPtr>& schemas,
589
                                  TabletSchemaSPtr& common_schema, int32_t variant_col_unique_id,
590
1.77k
                                  std::set<PathInData>* path_set) {
591
1.77k
    std::map<std::string, TabletColumnPtr> typed_columns;
592
1.77k
    for (const TabletColumnPtr& col :
593
7.87k
         common_schema->column_by_uid(variant_col_unique_id).get_sub_columns()) {
594
7.87k
        typed_columns[col->name()] = col;
595
7.87k
    }
596
    // Types of subcolumns by path from all tuples.
597
1.77k
    std::map<PathInData, DataTypes> subcolumns_types;
598
599
    // Collect all paths first to enable batch checking
600
1.77k
    std::vector<PathInData> all_paths;
601
602
1.95k
    for (const TabletSchemaSPtr& schema : schemas) {
603
6.34k
        for (const TabletColumnPtr& col : schema->columns()) {
604
            // Get subcolumns of this variant
605
6.34k
            if (col->has_path_info() && col->parent_unique_id() >= 0 &&
606
6.34k
                col->parent_unique_id() == variant_col_unique_id) {
607
949
                subcolumns_types[*col->path_info_ptr()].emplace_back(
608
949
                        DataTypeFactory::instance().create_data_type(*col, col->is_nullable()));
609
949
                all_paths.push_back(*col->path_info_ptr());
610
949
            }
611
6.34k
        }
612
1.95k
    }
613
614
    // Batch check for conflicts
615
1.77k
    RETURN_IF_ERROR(check_variant_has_no_ambiguous_paths(all_paths));
616
617
1.77k
    return update_least_schema_internal(subcolumns_types, common_schema, variant_col_unique_id,
618
1.77k
                                        typed_columns, path_set);
619
1.77k
}
620
621
// Keep variant subcolumn BF support aligned with FE DDL checks.
622
140k
bool is_bf_supported_by_fe_for_variant_subcolumn(FieldType type) {
623
140k
    switch (type) {
624
91
    case FieldType::OLAP_FIELD_TYPE_SMALLINT:
625
436
    case FieldType::OLAP_FIELD_TYPE_INT:
626
107k
    case FieldType::OLAP_FIELD_TYPE_BIGINT:
627
108k
    case FieldType::OLAP_FIELD_TYPE_LARGEINT:
628
108k
    case FieldType::OLAP_FIELD_TYPE_CHAR:
629
108k
    case FieldType::OLAP_FIELD_TYPE_VARCHAR:
630
128k
    case FieldType::OLAP_FIELD_TYPE_STRING:
631
128k
    case FieldType::OLAP_FIELD_TYPE_DATE:
632
128k
    case FieldType::OLAP_FIELD_TYPE_DATETIME:
633
128k
    case FieldType::OLAP_FIELD_TYPE_DATEV2:
634
128k
    case FieldType::OLAP_FIELD_TYPE_DATETIMEV2:
635
128k
    case FieldType::OLAP_FIELD_TYPE_TIMESTAMPTZ:
636
128k
    case FieldType::OLAP_FIELD_TYPE_DECIMAL:
637
128k
    case FieldType::OLAP_FIELD_TYPE_DECIMAL32:
638
128k
    case FieldType::OLAP_FIELD_TYPE_DECIMAL64:
639
129k
    case FieldType::OLAP_FIELD_TYPE_DECIMAL128I:
640
129k
    case FieldType::OLAP_FIELD_TYPE_DECIMAL256:
641
129k
    case FieldType::OLAP_FIELD_TYPE_IPV4:
642
129k
    case FieldType::OLAP_FIELD_TYPE_IPV6:
643
129k
        return true;
644
10.9k
    default:
645
10.9k
        return false;
646
140k
    }
647
140k
}
648
649
void inherit_column_attributes(const TabletColumn& source, TabletColumn& target,
650
140k
                               TabletSchemaSPtr* target_schema) {
651
140k
    if (!target.is_extracted_column()) {
652
0
        return;
653
0
    }
654
140k
    target.set_aggregation_method(source.aggregation());
655
656
    // 1. bloom filter
657
140k
    if (is_bf_supported_by_fe_for_variant_subcolumn(target.type())) {
658
129k
        target.set_is_bf_column(source.is_bf_column());
659
129k
    }
660
661
140k
    if (!target_schema) {
662
134k
        return;
663
134k
    }
664
665
    // 2. inverted index
666
6.38k
    TabletIndexes indexes_to_add;
667
6.38k
    auto source_indexes = (*target_schema)->inverted_indexs(source.unique_id());
668
    // if target is variant type, we need to inherit all indexes
669
    // because this schema is a read schema from fe
670
6.38k
    if (target.is_variant_type()) {
671
5.47k
        for (auto& index : source_indexes) {
672
409
            auto index_info = std::make_shared<TabletIndex>(*index);
673
409
            index_info->set_escaped_escaped_index_suffix_path(target.path_info_ptr()->get_path());
674
409
            indexes_to_add.emplace_back(std::move(index_info));
675
409
        }
676
5.47k
    } else {
677
908
        inherit_index(source_indexes, indexes_to_add, target);
678
908
    }
679
6.38k
    auto target_indexes = (*target_schema)
680
6.38k
                                  ->inverted_indexs(target.parent_unique_id(),
681
6.38k
                                                    target.path_info_ptr()->get_path());
682
6.39k
    if (target_indexes.empty()) {
683
6.39k
        for (auto& index_info : indexes_to_add) {
684
417
            (*target_schema)->append_index(std::move(*index_info));
685
417
        }
686
6.39k
    }
687
688
    // 3. TODO: gnragm bf index
689
6.38k
}
690
691
7.66k
void inherit_column_attributes(TabletSchemaSPtr& schema) {
692
    // Add index meta if extracted column is missing index meta
693
103k
    for (size_t i = 0; i < schema->num_columns(); ++i) {
694
95.7k
        TabletColumn& col = schema->mutable_column(i);
695
95.7k
        if (!col.is_extracted_column()) {
696
89.3k
            continue;
697
89.3k
        }
698
6.42k
        if (schema->field_index(col.parent_unique_id()) == -1) {
699
            // parent column is missing, maybe dropped
700
0
            continue;
701
0
        }
702
6.42k
        inherit_column_attributes(schema->column_by_uid(col.parent_unique_id()), col, &schema);
703
6.42k
    }
704
7.66k
}
705
706
Status get_least_common_schema(const std::vector<TabletSchemaSPtr>& schemas,
707
                               const TabletSchemaSPtr& base_schema, TabletSchemaSPtr& output_schema,
708
1.73k
                               bool check_schema_size) {
709
1.73k
    std::vector<int32_t> variant_column_unique_id;
710
    // Construct a schema excluding the extracted columns and gather unique identifiers for variants.
711
    // Ensure that the output schema also excludes these extracted columns. This approach prevents
712
    // duplicated paths following the update_least_common_schema process.
713
1.73k
    auto build_schema_without_extracted_columns = [&](const TabletSchemaSPtr& base_schema) {
714
1.73k
        output_schema = std::make_shared<TabletSchema>();
715
        // not copy columns but only shadow copy other attributes
716
1.73k
        output_schema->shawdow_copy_without_columns(*base_schema);
717
        // Get all columns without extracted columns and collect variant col unique id
718
4.63k
        for (const TabletColumnPtr& col : base_schema->columns()) {
719
4.63k
            if (col->is_variant_type()) {
720
1.77k
                variant_column_unique_id.push_back(col->unique_id());
721
1.77k
            }
722
4.63k
            if (!col->is_extracted_column()) {
723
4.14k
                output_schema->append_column(*col);
724
4.14k
            }
725
4.63k
        }
726
1.73k
    };
727
1.73k
    if (base_schema == nullptr) {
728
        // Pick tablet schema with max schema version
729
324
        auto max_version_schema =
730
324
                *std::max_element(schemas.cbegin(), schemas.cend(),
731
1.41k
                                  [](const TabletSchemaSPtr a, const TabletSchemaSPtr b) {
732
1.41k
                                      return a->schema_version() < b->schema_version();
733
1.41k
                                  });
734
324
        CHECK(max_version_schema);
735
324
        build_schema_without_extracted_columns(max_version_schema);
736
1.41k
    } else {
737
        // use input base_schema schema as base schema
738
1.41k
        build_schema_without_extracted_columns(base_schema);
739
1.41k
    }
740
741
1.77k
    for (int32_t unique_id : variant_column_unique_id) {
742
1.77k
        std::set<PathInData> path_set;
743
1.77k
        RETURN_IF_ERROR(update_least_common_schema(schemas, output_schema, unique_id, &path_set));
744
1.77k
    }
745
746
1.73k
    inherit_column_attributes(output_schema);
747
1.73k
    if (check_schema_size &&
748
1.73k
        output_schema->columns().size() > config::variant_max_merged_tablet_schema_size) {
749
0
        return Status::DataQualityError("Reached max column size limit {}",
750
0
                                        config::variant_max_merged_tablet_schema_size);
751
0
    }
752
753
1.73k
    return Status::OK();
754
1.73k
}
755
756
// sort by paths in lexicographical order
757
11.9k
ColumnVariant::Subcolumns get_sorted_subcolumns(const ColumnVariant::Subcolumns& subcolumns) {
758
    // sort by paths in lexicographical order
759
11.9k
    ColumnVariant::Subcolumns sorted = subcolumns;
760
687k
    std::sort(sorted.begin(), sorted.end(), [](const auto& lhsItem, const auto& rhsItem) {
761
687k
        return lhsItem->path < rhsItem->path;
762
687k
    });
763
11.9k
    return sorted;
764
11.9k
}
765
766
bool has_schema_index_diff(const TabletSchema* new_schema, const TabletSchema* old_schema,
767
23.8k
                           int32_t new_col_idx, int32_t old_col_idx) {
768
23.8k
    const auto& column_new = new_schema->column(new_col_idx);
769
23.8k
    const auto& column_old = old_schema->column(old_col_idx);
770
771
23.8k
    if (column_new.is_bf_column() != column_old.is_bf_column()) {
772
94
        return true;
773
94
    }
774
775
23.7k
    auto new_schema_inverted_indexs = new_schema->inverted_indexs(column_new);
776
23.7k
    auto old_schema_inverted_indexs = old_schema->inverted_indexs(column_old);
777
778
23.7k
    if (new_schema_inverted_indexs.size() != old_schema_inverted_indexs.size()) {
779
704
        return true;
780
704
    }
781
782
23.3k
    for (size_t i = 0; i < new_schema_inverted_indexs.size(); ++i) {
783
392
        if (!new_schema_inverted_indexs[i]->is_same_except_id(old_schema_inverted_indexs[i])) {
784
20
            return true;
785
20
        }
786
392
    }
787
788
23.0k
    return false;
789
23.0k
}
790
791
1.16k
TabletColumn create_sparse_column(const TabletColumn& variant) {
792
1.16k
    TabletColumn res;
793
1.16k
    res.set_name(variant.name_lower_case() + "." + SPARSE_COLUMN_PATH);
794
1.16k
    res.set_type(FieldType::OLAP_FIELD_TYPE_MAP);
795
1.16k
    res.set_aggregation_method(variant.aggregation());
796
1.16k
    res.set_path_info(PathInData {variant.name_lower_case() + "." + SPARSE_COLUMN_PATH});
797
1.16k
    res.set_parent_unique_id(variant.unique_id());
798
    // set default value to "NULL" DefaultColumnIterator will call insert_many_defaults
799
1.16k
    res.set_default_value("NULL");
800
1.16k
    TabletColumn child_tcolumn;
801
1.16k
    child_tcolumn.set_type(FieldType::OLAP_FIELD_TYPE_STRING);
802
1.16k
    res.add_sub_column(child_tcolumn);
803
1.16k
    res.add_sub_column(child_tcolumn);
804
1.16k
    return res;
805
1.16k
}
806
807
26.8k
TabletColumn create_sparse_shard_column(const TabletColumn& variant, int bucket_index) {
808
26.8k
    TabletColumn res;
809
26.8k
    std::string name = variant.name_lower_case() + "." + SPARSE_COLUMN_PATH + ".b" +
810
26.8k
                       std::to_string(bucket_index);
811
26.8k
    res.set_name(name);
812
26.8k
    res.set_type(FieldType::OLAP_FIELD_TYPE_MAP);
813
26.8k
    res.set_aggregation_method(variant.aggregation());
814
26.8k
    res.set_parent_unique_id(variant.unique_id());
815
26.8k
    res.set_default_value("NULL");
816
26.8k
    PathInData path(name);
817
26.8k
    res.set_path_info(path);
818
26.8k
    TabletColumn child_tcolumn;
819
26.8k
    child_tcolumn.set_type(FieldType::OLAP_FIELD_TYPE_STRING);
820
26.8k
    res.add_sub_column(child_tcolumn);
821
26.8k
    res.add_sub_column(child_tcolumn);
822
26.8k
    return res;
823
26.8k
}
824
825
6.28k
TabletColumn create_doc_value_column(const TabletColumn& variant, int bucket_index) {
826
6.28k
    TabletColumn res;
827
6.28k
    std::string name = variant.name_lower_case() + "." + DOC_VALUE_COLUMN_PATH + ".b" +
828
6.28k
                       std::to_string(bucket_index);
829
6.28k
    res.set_name(name);
830
6.28k
    res.set_type(FieldType::OLAP_FIELD_TYPE_MAP);
831
6.28k
    res.set_aggregation_method(variant.aggregation());
832
6.28k
    res.set_parent_unique_id(variant.unique_id());
833
6.28k
    res.set_default_value("NULL");
834
6.28k
    res.set_path_info(PathInData {name});
835
836
6.28k
    TabletColumn child_tcolumn;
837
6.28k
    child_tcolumn.set_type(FieldType::OLAP_FIELD_TYPE_STRING);
838
6.28k
    res.add_sub_column(child_tcolumn);
839
6.28k
    res.add_sub_column(child_tcolumn);
840
6.28k
    return res;
841
6.28k
}
842
843
286k
uint32_t variant_binary_shard_of(const StringRef& path, uint32_t bucket_num) {
844
286k
    if (bucket_num <= 1) return 0;
845
275k
    SipHash hash;
846
275k
    hash.update(path.data, path.size);
847
275k
    uint64_t h = hash.get64();
848
275k
    return static_cast<uint32_t>(h % bucket_num);
849
286k
}
850
851
Status VariantCompactionUtil::aggregate_path_to_stats(
852
        const RowsetSharedPtr& rs,
853
3.96k
        std::unordered_map<int32_t, PathToNoneNullValues>* uid_to_path_stats) {
854
3.96k
    SegmentCacheHandle segment_cache;
855
3.96k
    RETURN_IF_ERROR(SegmentLoader::instance()->load_segments(
856
3.96k
            std::static_pointer_cast<BetaRowset>(rs), &segment_cache));
857
858
10.6k
    for (const auto& column : rs->tablet_schema()->columns()) {
859
10.6k
        if (!column->is_variant_type() || column->unique_id() < 0) {
860
5.54k
            continue;
861
5.54k
        }
862
5.06k
        if (!should_check_variant_path_stats(*column)) {
863
0
            continue;
864
0
        }
865
        // Pure doc-mode columns have no sparse/subcolumn stats to aggregate
866
        // (all data is in the doc_value column). Skip to avoid unnecessary
867
        // external meta loading per source segment.
868
5.06k
        if (column->variant_enable_doc_mode()) {
869
1.16k
            continue;
870
1.16k
        }
871
3.89k
        for (const auto& segment : segment_cache.get_segments()) {
872
2.46k
            std::shared_ptr<ColumnReader> column_reader;
873
2.46k
            OlapReaderStatistics stats;
874
2.46k
            RETURN_IF_ERROR(
875
2.46k
                    segment->get_column_reader(column->unique_id(), &column_reader, &stats));
876
2.46k
            if (!column_reader) {
877
0
                continue;
878
0
            }
879
880
2.46k
            CHECK(column_reader->get_meta_type() == FieldType::OLAP_FIELD_TYPE_VARIANT);
881
2.46k
            auto* variant_column_reader =
882
2.46k
                    assert_cast<segment_v2::VariantColumnReader*>(column_reader.get());
883
            // load external meta before getting stats
884
2.46k
            RETURN_IF_ERROR(variant_column_reader->load_external_meta_once());
885
2.46k
            const auto* source_stats = variant_column_reader->get_stats();
886
2.46k
            CHECK(source_stats);
887
888
            // agg path -> stats
889
9.49k
            for (const auto& [path, size] : source_stats->sparse_column_non_null_size) {
890
9.49k
                (*uid_to_path_stats)[column->unique_id()][path] += size;
891
9.49k
            }
892
893
5.68k
            for (const auto& [path, size] : source_stats->subcolumns_non_null_size) {
894
5.68k
                (*uid_to_path_stats)[column->unique_id()][path] += size;
895
5.68k
            }
896
2.46k
        }
897
3.89k
    }
898
3.96k
    return Status::OK();
899
3.96k
}
900
901
Status VariantCompactionUtil::aggregate_variant_extended_info(
902
        const RowsetSharedPtr& rs,
903
5.79k
        std::unordered_map<int32_t, VariantExtendedInfo>* uid_to_variant_extended_info) {
904
5.79k
    SegmentCacheHandle segment_cache;
905
5.79k
    RETURN_IF_ERROR(SegmentLoader::instance()->load_segments(
906
5.79k
            std::static_pointer_cast<BetaRowset>(rs), &segment_cache));
907
908
20.7k
    for (const auto& column : rs->tablet_schema()->columns()) {
909
20.7k
        if (!column->is_variant_type()) {
910
13.6k
            continue;
911
13.6k
        }
912
7.04k
        auto& extended_info = (*uid_to_variant_extended_info)[column->unique_id()];
913
7.04k
        if (column->variant_enable_nested_group()) {
914
0
            extended_info.has_nested_group = true;
915
0
        }
916
7.04k
        for (const auto& segment : segment_cache.get_segments()) {
917
4.46k
            std::shared_ptr<ColumnReader> column_reader;
918
4.46k
            OlapReaderStatistics stats;
919
4.46k
            RETURN_IF_ERROR(
920
4.46k
                    segment->get_column_reader(column->unique_id(), &column_reader, &stats));
921
4.46k
            if (!column_reader) {
922
0
                continue;
923
0
            }
924
925
4.46k
            CHECK(column_reader->get_meta_type() == FieldType::OLAP_FIELD_TYPE_VARIANT);
926
4.46k
            auto* variant_column_reader =
927
4.46k
                    assert_cast<segment_v2::VariantColumnReader*>(column_reader.get());
928
4.46k
            const auto* source_stats = variant_column_reader->get_stats();
929
4.46k
            CHECK(source_stats);
930
931
            // For pure doc mode, only need to detect has_doc_value_segments from
932
            // stats (available from init, no external meta load needed). Also
933
            // accumulate per-path counts so VariantDocCompactWriter can pre-reserve
934
            // its sparse-subcolumn rowid vectors instead of paying PaddedPODArray
935
            // 2x growth waste.
936
4.46k
            if (column->variant_enable_doc_mode() &&
937
4.46k
                source_stats->has_doc_value_column_non_null_size()) {
938
690
                extended_info.has_doc_value_segments = true;
939
3.10k
                for (const auto& [path, cnt] : source_stats->doc_value_column_non_null_size) {
940
3.10k
                    extended_info.doc_value_path_total_counts[path] += cnt;
941
3.10k
                }
942
690
                continue;
943
690
            }
944
945
            // load external meta for subcolumn info (paths, types, etc.)
946
3.77k
            RETURN_IF_ERROR(variant_column_reader->load_external_meta_once());
947
948
3.77k
            if (!column->variant_enable_nested_group()) {
949
                // NG roots still need type metadata for regular subpaths such as `v.owner`,
950
                // but their compaction schema should not be driven by flat path stats.
951
4.52k
                for (const auto& [path, size] : source_stats->sparse_column_non_null_size) {
952
4.52k
                    extended_info.path_to_none_null_values[path] += size;
953
4.52k
                    extended_info.sparse_paths.emplace(path);
954
4.52k
                }
955
956
6.83k
                for (const auto& [path, size] : source_stats->subcolumns_non_null_size) {
957
6.83k
                    extended_info.path_to_none_null_values[path] += size;
958
6.83k
                }
959
3.77k
            }
960
961
            //2. agg path -> schema
962
3.77k
            variant_column_reader->get_subcolumns_types(&extended_info.path_to_data_types);
963
964
            // 3. extract typed paths
965
3.77k
            variant_column_reader->get_typed_paths(&extended_info.typed_paths);
966
967
            // 4. extract nested paths
968
3.77k
            if (!column->variant_enable_nested_group()) {
969
3.77k
                variant_column_reader->get_nested_paths(&extended_info.nested_paths);
970
3.77k
            }
971
3.77k
        }
972
7.04k
    }
973
5.79k
    return Status::OK();
974
5.79k
}
975
976
// get the subpaths and sparse paths for the variant column
977
void VariantCompactionUtil::get_subpaths(int32_t max_subcolumns_count,
978
                                         const PathToNoneNullValues& stats,
979
548
                                         TabletSchema::PathsSetInfo& paths_set_info) {
980
    // max_subcolumns_count is 0 means no limit
981
548
    if (max_subcolumns_count > 0 && stats.size() > max_subcolumns_count) {
982
250
        std::vector<std::pair<size_t, std::string_view>> paths_with_sizes;
983
250
        paths_with_sizes.reserve(stats.size());
984
5.14k
        for (const auto& [path, size] : stats) {
985
5.14k
            paths_with_sizes.emplace_back(size, path);
986
5.14k
        }
987
250
        std::sort(paths_with_sizes.begin(), paths_with_sizes.end(), std::greater());
988
989
        // Select top N paths as subcolumns, remaining paths as sparse columns
990
5.14k
        for (const auto& [size, path] : paths_with_sizes) {
991
5.14k
            if (paths_set_info.sub_path_set.size() < max_subcolumns_count) {
992
943
                paths_set_info.sub_path_set.emplace(path);
993
4.19k
            } else {
994
4.19k
                paths_set_info.sparse_path_set.emplace(path);
995
4.19k
            }
996
5.14k
        }
997
250
        LOG(INFO) << "subpaths " << paths_set_info.sub_path_set.size() << " sparse paths "
998
250
                  << paths_set_info.sparse_path_set.size() << " variant max subcolumns count "
999
250
                  << max_subcolumns_count << " stats size " << paths_with_sizes.size();
1000
298
    } else {
1001
        // Apply all paths as subcolumns
1002
719
        for (const auto& [path, _] : stats) {
1003
719
            paths_set_info.sub_path_set.emplace(path);
1004
719
        }
1005
298
    }
1006
548
}
1007
1008
Status VariantCompactionUtil::check_path_stats(const std::vector<RowsetSharedPtr>& intputs,
1009
8.60k
                                               RowsetSharedPtr output, BaseTabletSPtr tablet) {
1010
8.60k
    if (output->tablet_schema()->num_variant_columns() == 0) {
1011
7.95k
        return Status::OK();
1012
7.95k
    }
1013
5.74k
    for (const auto& rowset : intputs) {
1014
20.6k
        for (const auto& column : rowset->tablet_schema()->columns()) {
1015
20.6k
            if (column->is_variant_type() && !should_check_variant_path_stats(*column)) {
1016
0
                return Status::OK();
1017
0
            }
1018
20.6k
        }
1019
5.74k
    }
1020
    // check no extended schema in input rowsets
1021
5.75k
    for (const auto& rowset : intputs) {
1022
20.6k
        for (const auto& column : rowset->tablet_schema()->columns()) {
1023
20.6k
            if (column->is_extracted_column()) {
1024
0
                return Status::OK();
1025
0
            }
1026
20.6k
        }
1027
5.75k
    }
1028
654
#ifndef BE_TEST
1029
    // check no extended schema in output rowset
1030
2.19k
    for (const auto& column : output->tablet_schema()->columns()) {
1031
2.19k
        if (column->is_extracted_column()) {
1032
0
            const auto& name = column->name();
1033
0
            if (name.find("." + DOC_VALUE_COLUMN_PATH + ".") != std::string::npos ||
1034
0
                name.find("." + SPARSE_COLUMN_PATH + ".") != std::string::npos ||
1035
0
                name.ends_with("." + SPARSE_COLUMN_PATH)) {
1036
0
                continue;
1037
0
            }
1038
0
            return Status::InternalError("Unexpected extracted column {} in output rowset",
1039
0
                                         column->name());
1040
0
        }
1041
2.19k
    }
1042
654
#endif
1043
    // only check path stats for dup_keys since the rows may be merged in other models
1044
654
    if (tablet->keys_type() != KeysType::DUP_KEYS) {
1045
194
        return Status::OK();
1046
194
    }
1047
    // if there is a delete predicate in the input rowsets, we skip the path stats check
1048
3.45k
    for (auto& rowset : intputs) {
1049
3.45k
        if (rowset->rowset_meta()->has_delete_predicate()) {
1050
4
            return Status::OK();
1051
4
        }
1052
3.45k
    }
1053
1.22k
    for (const auto& column : output->tablet_schema()->columns()) {
1054
1.22k
        if (column->is_variant_type() && !should_check_variant_path_stats(*column)) {
1055
0
            return Status::OK();
1056
0
        }
1057
1.22k
    }
1058
456
    std::unordered_map<int32_t, PathToNoneNullValues> original_uid_to_path_stats;
1059
3.43k
    for (const auto& rs : intputs) {
1060
3.43k
        RETURN_IF_ERROR(aggregate_path_to_stats(rs, &original_uid_to_path_stats));
1061
3.43k
    }
1062
456
    std::unordered_map<int32_t, PathToNoneNullValues> output_uid_to_path_stats;
1063
456
    RETURN_IF_ERROR(aggregate_path_to_stats(output, &output_uid_to_path_stats));
1064
456
    for (const auto& [uid, stats] : output_uid_to_path_stats) {
1065
289
        if (output->tablet_schema()->column_by_uid(uid).is_variant_type() &&
1066
289
            output->tablet_schema()->column_by_uid(uid).variant_enable_doc_mode()) {
1067
0
            continue;
1068
0
        }
1069
289
        if (original_uid_to_path_stats.find(uid) == original_uid_to_path_stats.end()) {
1070
0
            return Status::InternalError("Path stats not found for uid {}, tablet_id {}", uid,
1071
0
                                         tablet->tablet_id());
1072
0
        }
1073
1074
        // In input rowsets, some rowsets may have statistics values exceeding the maximum limit,
1075
        // which leads to inaccurate statistics
1076
289
        if (stats.size() > output->tablet_schema()
1077
289
                                   ->column_by_uid(uid)
1078
289
                                   .variant_max_sparse_column_statistics_size()) {
1079
            // When there is only one segment, we can ensure that the size of each path in output stats is accurate
1080
1
            if (output->num_segments() == 1) {
1081
13
                for (const auto& [path, size] : stats) {
1082
13
                    if (original_uid_to_path_stats.at(uid).find(path) ==
1083
13
                        original_uid_to_path_stats.at(uid).end()) {
1084
0
                        continue;
1085
0
                    }
1086
13
                    if (original_uid_to_path_stats.at(uid).at(path) > size) {
1087
0
                        return Status::InternalError(
1088
0
                                "Path stats not smaller for uid {} with path `{}`, input size {}, "
1089
0
                                "output "
1090
0
                                "size {}, "
1091
0
                                "tablet_id {}",
1092
0
                                uid, path, original_uid_to_path_stats.at(uid).at(path), size,
1093
0
                                tablet->tablet_id());
1094
0
                    }
1095
13
                }
1096
1
            }
1097
1
        }
1098
        // in this case, input stats is accurate, so we check the stats size and stats value
1099
288
        else {
1100
4.50k
            for (const auto& [path, size] : stats) {
1101
4.50k
                if (original_uid_to_path_stats.at(uid).find(path) ==
1102
4.50k
                    original_uid_to_path_stats.at(uid).end()) {
1103
0
                    return Status::InternalError(
1104
0
                            "Path stats not found for uid {}, path {}, tablet_id {}", uid, path,
1105
0
                            tablet->tablet_id());
1106
0
                }
1107
4.50k
                if (original_uid_to_path_stats.at(uid).at(path) != size) {
1108
103
                    return Status::InternalError(
1109
103
                            "Path stats not match for uid {} with path `{}`, input size {}, output "
1110
103
                            "size {}, "
1111
103
                            "tablet_id {}",
1112
103
                            uid, path, original_uid_to_path_stats.at(uid).at(path), size,
1113
103
                            tablet->tablet_id());
1114
103
                }
1115
4.50k
            }
1116
288
        }
1117
289
    }
1118
1119
353
    return Status::OK();
1120
456
}
1121
1122
Status VariantCompactionUtil::get_compaction_typed_columns(
1123
        const TabletSchemaSPtr& target, const std::unordered_set<std::string>& typed_paths,
1124
        const TabletColumnPtr parent_column, TabletSchemaSPtr& output_schema,
1125
623
        TabletSchema::PathsSetInfo& paths_set_info) {
1126
623
    if (parent_column->variant_enable_typed_paths_to_sparse()) {
1127
40
        return Status::OK();
1128
40
    }
1129
583
    for (const auto& path : typed_paths) {
1130
418
        TabletSchema::SubColumnInfo sub_column_info;
1131
418
        if (generate_sub_column_info(*target, parent_column->unique_id(), path, &sub_column_info)) {
1132
417
            inherit_column_attributes(*parent_column, sub_column_info.column);
1133
417
            output_schema->append_column(sub_column_info.column);
1134
417
            paths_set_info.typed_path_set.insert({path, std::move(sub_column_info)});
1135
417
            VLOG_DEBUG << "append typed column " << path;
1136
417
        } else {
1137
1
            return Status::InternalError("Failed to generate sub column info for path {}", path);
1138
1
        }
1139
418
    }
1140
582
    return Status::OK();
1141
583
}
1142
1143
Status VariantCompactionUtil::get_compaction_nested_columns(
1144
        const std::unordered_set<PathInData, PathInData::Hash>& nested_paths,
1145
        const PathToDataTypes& path_to_data_types, const TabletColumnPtr parent_column,
1146
540
        TabletSchemaSPtr& output_schema, TabletSchema::PathsSetInfo& paths_set_info) {
1147
540
    const auto& parent_indexes = output_schema->inverted_indexs(parent_column->unique_id());
1148
540
    for (const auto& path : nested_paths) {
1149
3
        const auto& find_data_types = path_to_data_types.find(path);
1150
3
        if (find_data_types == path_to_data_types.end() || find_data_types->second.empty()) {
1151
1
            return Status::InternalError("Nested path {} has no data type", path.get_path());
1152
1
        }
1153
2
        DataTypePtr data_type;
1154
2
        get_least_supertype_jsonb(find_data_types->second, &data_type);
1155
1156
2
        const std::string& column_name = parent_column->name_lower_case() + "." + path.get_path();
1157
2
        PathInDataBuilder full_path_builder;
1158
2
        auto full_path = full_path_builder.append(parent_column->name_lower_case(), false)
1159
2
                                 .append(path.get_parts(), false)
1160
2
                                 .build();
1161
2
        TabletColumn nested_column =
1162
2
                get_column_by_type(data_type, column_name,
1163
2
                                   ExtraInfo {.unique_id = -1,
1164
2
                                              .parent_unique_id = parent_column->unique_id(),
1165
2
                                              .path_info = full_path});
1166
2
        inherit_column_attributes(*parent_column, nested_column);
1167
2
        TabletIndexes sub_column_indexes;
1168
2
        inherit_index(parent_indexes, sub_column_indexes, nested_column);
1169
2
        paths_set_info.subcolumn_indexes.emplace(path.get_path(), std::move(sub_column_indexes));
1170
2
        output_schema->append_column(nested_column);
1171
2
        VLOG_DEBUG << "append nested column " << path.get_path();
1172
2
    }
1173
539
    return Status::OK();
1174
540
}
1175
1176
void VariantCompactionUtil::get_compaction_subcolumns_from_subpaths(
1177
        TabletSchema::PathsSetInfo& paths_set_info, const TabletColumnPtr parent_column,
1178
        const TabletSchemaSPtr& target, const PathToDataTypes& path_to_data_types,
1179
541
        const std::unordered_set<std::string>& sparse_paths, TabletSchemaSPtr& output_schema) {
1180
541
    auto& path_set = paths_set_info.sub_path_set;
1181
541
    std::vector<StringRef> sorted_subpaths(path_set.begin(), path_set.end());
1182
541
    std::sort(sorted_subpaths.begin(), sorted_subpaths.end());
1183
541
    const auto& parent_indexes = target->inverted_indexs(parent_column->unique_id());
1184
    // append subcolumns
1185
1.60k
    for (const auto& subpath : sorted_subpaths) {
1186
1.60k
        auto column_name = parent_column->name_lower_case() + "." + subpath.to_string();
1187
1.60k
        auto column_path = PathInData(column_name);
1188
1189
1.60k
        const auto& find_data_types = path_to_data_types.find(PathInData(subpath));
1190
1191
        // some cases: the subcolumn type is variant
1192
        // 1. this path has no data type in segments
1193
        // 2. this path is in sparse paths
1194
        // 3. the sparse paths are too much
1195
1.60k
        TabletSchema::SubColumnInfo sub_column_info;
1196
1.60k
        if (parent_column->variant_enable_typed_paths_to_sparse() &&
1197
1.60k
            generate_sub_column_info(*target, parent_column->unique_id(), std::string(subpath),
1198
72
                                     &sub_column_info)) {
1199
62
            inherit_column_attributes(*parent_column, sub_column_info.column);
1200
62
            output_schema->append_column(sub_column_info.column);
1201
62
            paths_set_info.subcolumn_indexes.emplace(subpath, std::move(sub_column_info.indexes));
1202
62
            VLOG_DEBUG << "append typed column " << subpath;
1203
1.54k
        } else if (find_data_types == path_to_data_types.end() || find_data_types->second.empty() ||
1204
1.54k
                   sparse_paths.find(std::string(subpath)) != sparse_paths.end() ||
1205
1.54k
                   sparse_paths.size() >=
1206
1.41k
                           parent_column->variant_max_sparse_column_statistics_size()) {
1207
135
            TabletColumn subcolumn;
1208
135
            subcolumn.set_name(column_name);
1209
135
            subcolumn.set_type(FieldType::OLAP_FIELD_TYPE_VARIANT);
1210
135
            subcolumn.set_parent_unique_id(parent_column->unique_id());
1211
135
            subcolumn.set_path_info(column_path);
1212
135
            subcolumn.set_aggregation_method(parent_column->aggregation());
1213
135
            subcolumn.set_variant_max_subcolumns_count(
1214
135
                    parent_column->variant_max_subcolumns_count());
1215
135
            subcolumn.set_variant_enable_doc_mode(parent_column->variant_enable_doc_mode());
1216
135
            subcolumn.set_is_nullable(true);
1217
135
            output_schema->append_column(subcolumn);
1218
135
            VLOG_DEBUG << "append sub column " << subpath << " data type "
1219
0
                       << "VARIANT";
1220
135
        }
1221
        // normal case: the subcolumn type can be calculated from the data types in segments
1222
1.40k
        else {
1223
1.40k
            DataTypePtr data_type;
1224
1.40k
            get_least_supertype_jsonb(find_data_types->second, &data_type);
1225
1.40k
            TabletColumn sub_column =
1226
1.40k
                    get_column_by_type(data_type, column_name,
1227
1.40k
                                       ExtraInfo {.unique_id = -1,
1228
1.40k
                                                  .parent_unique_id = parent_column->unique_id(),
1229
1.40k
                                                  .path_info = column_path});
1230
1.40k
            inherit_column_attributes(*parent_column, sub_column);
1231
1.40k
            TabletIndexes sub_column_indexes;
1232
1.40k
            inherit_index(parent_indexes, sub_column_indexes, sub_column);
1233
1.40k
            paths_set_info.subcolumn_indexes.emplace(subpath, std::move(sub_column_indexes));
1234
1.40k
            output_schema->append_column(sub_column);
1235
1.40k
            VLOG_DEBUG << "append sub column " << subpath << " data type " << data_type->get_name();
1236
1.40k
        }
1237
1.60k
    }
1238
541
}
1239
1240
void VariantCompactionUtil::get_compaction_subcolumns_from_data_types(
1241
        TabletSchema::PathsSetInfo& paths_set_info, const TabletColumnPtr parent_column,
1242
        const TabletSchemaSPtr& target, const PathToDataTypes& path_to_data_types,
1243
90
        TabletSchemaSPtr& output_schema) {
1244
90
    const auto& parent_indexes = target->inverted_indexs(parent_column->unique_id());
1245
237
    for (const auto& [path, data_types] : path_to_data_types) {
1246
        // Typed paths are materialized by get_compaction_typed_columns(); this helper only
1247
        // materializes regular subcolumns inferred from rowset data types.
1248
237
        if (data_types.empty() || path.empty() || path.get_is_typed() || path.has_nested_part()) {
1249
55
            continue;
1250
55
        }
1251
        // Skip paths already handled by get_compaction_typed_columns
1252
182
        if (paths_set_info.typed_path_set.contains(path.get_path())) {
1253
0
            continue;
1254
0
        }
1255
182
        DataTypePtr data_type;
1256
182
        get_least_supertype_jsonb(data_types, &data_type);
1257
182
        auto column_name = parent_column->name_lower_case() + "." + path.get_path();
1258
182
        auto column_path = PathInData(column_name);
1259
182
        TabletColumn sub_column =
1260
182
                get_column_by_type(data_type, column_name,
1261
182
                                   ExtraInfo {.unique_id = -1,
1262
182
                                              .parent_unique_id = parent_column->unique_id(),
1263
182
                                              .path_info = column_path});
1264
182
        inherit_column_attributes(*parent_column, sub_column);
1265
182
        TabletIndexes sub_column_indexes;
1266
182
        inherit_index(parent_indexes, sub_column_indexes, sub_column);
1267
182
        paths_set_info.sub_path_set.emplace(path.get_path());
1268
182
        paths_set_info.subcolumn_indexes.emplace(path.get_path(), std::move(sub_column_indexes));
1269
182
        output_schema->append_column(sub_column);
1270
182
        VLOG_DEBUG << "append sub column " << path.get_path() << " data type "
1271
0
                   << data_type->get_name();
1272
182
    }
1273
90
}
1274
1275
// Build the temporary schema for compaction.
1276
// NestedGroup roots are special: the root VARIANT column owns the NG tree and the streaming NG
1277
// writer handles NG children, while regular non-NG paths beside the arrays are materialized as
1278
// ordinary extracted subcolumns. NG typed paths still use get_compaction_typed_columns(), keeping
1279
// typed-column rules out of the NG-specific regular-path filtering.
1280
Status VariantCompactionUtil::get_extended_compaction_schema(
1281
        const std::vector<RowsetSharedPtr>& rowsets, TabletSchemaSPtr& target,
1282
        std::unordered_map<int32_t, std::shared_ptr<segment_v2::VariantDocPathStats>>*
1283
8.17k
                doc_path_stats_out) {
1284
8.17k
    std::unordered_map<int32_t, VariantExtendedInfo> uid_to_variant_extended_info;
1285
8.17k
    const bool needs_variant_extended_info =
1286
90.7k
            std::ranges::any_of(target->columns(), [](const TabletColumnPtr& column) {
1287
90.7k
                return column->is_variant_type() && (should_check_variant_path_stats(*column) ||
1288
676
                                                     column->variant_enable_nested_group());
1289
90.7k
            });
1290
8.17k
    if (needs_variant_extended_info) {
1291
        // collect path stats from all rowsets and segments
1292
5.79k
        for (const auto& rs : rowsets) {
1293
5.79k
            RETURN_IF_ERROR(aggregate_variant_extended_info(rs, &uid_to_variant_extended_info));
1294
5.79k
        }
1295
675
    }
1296
1297
    // build the output schema
1298
8.17k
    TabletSchemaSPtr output_schema = std::make_shared<TabletSchema>();
1299
8.17k
    output_schema->shawdow_copy_without_columns(*target);
1300
8.17k
    std::unordered_map<int32_t, TabletSchema::PathsSetInfo> uid_to_paths_set_info;
1301
8.17k
    const auto ng_root_uids =
1302
8.17k
            collect_nested_group_compaction_root_uids(target, uid_to_variant_extended_info);
1303
92.7k
    for (const TabletColumnPtr& column : target->columns()) {
1304
92.7k
        if (!column->is_extracted_column()) {
1305
92.6k
            output_schema->append_column(*column);
1306
92.6k
        }
1307
92.7k
        if (!column->is_variant_type()) {
1308
92.0k
            continue;
1309
92.0k
        }
1310
18.4E
        VLOG_DEBUG << "column " << column->name() << " unique id " << column->unique_id();
1311
1312
747
        const auto info_it = uid_to_variant_extended_info.find(column->unique_id());
1313
747
        const VariantExtendedInfo empty_extended_info;
1314
747
        const VariantExtendedInfo& extended_info = info_it == uid_to_variant_extended_info.end()
1315
747
                                                           ? empty_extended_info
1316
747
                                                           : info_it->second;
1317
747
        auto& paths_set_info = uid_to_paths_set_info[column->unique_id()];
1318
747
        const bool use_nested_group_compaction_schema = ng_root_uids.contains(column->unique_id());
1319
1320
747
        if (use_nested_group_compaction_schema) {
1321
            // 1. append typed columns. Keep this shared with the non-NG typed helper; only the
1322
            // regular-path selection below is NG-specific.
1323
1
            RETURN_IF_ERROR(get_compaction_typed_columns(target, extended_info.typed_paths, column,
1324
1
                                                         output_schema, paths_set_info));
1325
1326
            // NG roots do not record path-count stats for ordinary Variant paths, so their regular
1327
            // non-NG subcolumns use the same data-types materialization helper as the
1328
            // all-materialized non-NG branch below.
1329
1
            auto regular_path_to_data_types =
1330
1
                    collect_regular_types_outside_nested_group(extended_info);
1331
1
            get_compaction_subcolumns_from_data_types(paths_set_info, column, target,
1332
1
                                                      regular_path_to_data_types, output_schema);
1333
1
            LOG(INFO) << "Variant column uid=" << column->unique_id()
1334
1
                      << " keeps nested-group root and materializes regular non-NG subcolumns in "
1335
1
                         "compaction schema";
1336
1
            continue;
1337
1
        }
1338
1339
746
        if (column->variant_enable_doc_mode()) {
1340
246
            const auto& info = uid_to_variant_extended_info[column->unique_id()];
1341
1342
246
            if (info.has_doc_value_segments) {
1343
                // At least one segment has doc-value data (all-doc or mixed).
1344
                // Output doc-value bucket columns.
1345
                // For mixed case, a new SubcolumnToDocCompactIterator will
1346
                // convert subcolumn data to doc-value format at read time.
1347
167
                const int bucket_num = std::max(1, column->variant_doc_hash_shard_count());
1348
1349
474
                for (int b = 0; b < bucket_num; ++b) {
1350
307
                    TabletColumn doc_value_bucket_column = create_doc_value_column(*column, b);
1351
307
                    doc_value_bucket_column.set_type(FieldType::OLAP_FIELD_TYPE_VARIANT);
1352
307
                    doc_value_bucket_column.set_is_nullable(false);
1353
307
                    doc_value_bucket_column.set_variant_enable_doc_mode(true);
1354
307
                    output_schema->append_column(doc_value_bucket_column);
1355
307
                }
1356
167
                continue;
1357
167
            }
1358
            // All segments were downgraded to subcolumn mode (path < threshold).
1359
            // All subcolumns are materialized, use get_compaction_subcolumns_from_data_types.
1360
            // But first, handle typed columns so their indexes (especially
1361
            // field_pattern-based ones) are correctly registered in typed_path_set.
1362
79
            RETURN_IF_ERROR(get_compaction_typed_columns(
1363
79
                    target, extended_info.typed_paths, column, output_schema,
1364
79
                    uid_to_paths_set_info[column->unique_id()]));
1365
1366
79
            get_compaction_subcolumns_from_data_types(
1367
79
                    uid_to_paths_set_info[column->unique_id()], column, target,
1368
79
                    uid_to_variant_extended_info[column->unique_id()].path_to_data_types,
1369
79
                    output_schema);
1370
79
            continue;
1371
79
        }
1372
1373
        // 1. append typed columns
1374
500
        RETURN_IF_ERROR(get_compaction_typed_columns(target, extended_info.typed_paths, column,
1375
500
                                                     output_schema, paths_set_info));
1376
1377
        // 2. append nested columns
1378
500
        RETURN_IF_ERROR(get_compaction_nested_columns(extended_info.nested_paths,
1379
500
                                                      extended_info.path_to_data_types, column,
1380
500
                                                      output_schema, paths_set_info));
1381
1382
        // 3. get the subpaths
1383
500
        get_subpaths(column->variant_max_subcolumns_count(), extended_info.path_to_none_null_values,
1384
500
                     paths_set_info);
1385
1386
        // 4. append subcolumns
1387
533
        if (column->variant_max_subcolumns_count() > 0 || !column->get_sub_columns().empty()) {
1388
533
            get_compaction_subcolumns_from_subpaths(paths_set_info, column, target,
1389
533
                                                    extended_info.path_to_data_types,
1390
533
                                                    extended_info.sparse_paths, output_schema);
1391
533
        }
1392
        // variant_max_subcolumns_count == 0 and no typed paths materialized
1393
        // it means that all subcolumns are materialized, may be from old data
1394
18.4E
        else {
1395
18.4E
            get_compaction_subcolumns_from_data_types(paths_set_info, column, target,
1396
18.4E
                                                      extended_info.path_to_data_types,
1397
18.4E
                                                      output_schema);
1398
18.4E
        }
1399
1400
        // append sparse column(s)
1401
        // If variant uses bucketized sparse columns, append one sparse bucket column per bucket.
1402
        // Otherwise, append the single sparse column.
1403
500
        int bucket_num = std::max(1, column->variant_sparse_hash_shard_count());
1404
504
        if (bucket_num > 1) {
1405
2.42k
            for (int b = 0; b < bucket_num; ++b) {
1406
1.92k
                TabletColumn sparse_bucket_column = create_sparse_shard_column(*column, b);
1407
1.92k
                output_schema->append_column(sparse_bucket_column);
1408
1.92k
            }
1409
18.4E
        } else {
1410
18.4E
            TabletColumn sparse_column = create_sparse_column(*column);
1411
18.4E
            output_schema->append_column(sparse_column);
1412
18.4E
        }
1413
500
    }
1414
1415
8.17k
    target = output_schema;
1416
    // used to merge & filter path to sparse column during reading in compaction
1417
8.17k
    target->set_path_set_info(std::move(uid_to_paths_set_info));
1418
1419
    // Convert aggregated path counts into bucket-partitioned VariantDocPathStats
1420
    // and hand back to the caller. Lets VariantDocCompactWriter pre-reserve its
1421
    // sparse accumulators (avoids PaddedPODArray 2x growth waste).
1422
8.17k
    if (doc_path_stats_out != nullptr) {
1423
8.15k
        for (auto& [uid, info] : uid_to_variant_extended_info) {
1424
789
            if (info.doc_value_path_total_counts.empty()) {
1425
619
                continue;
1426
619
            }
1427
170
            const TabletColumn* parent = nullptr;
1428
524
            for (const auto& col : target->columns()) {
1429
524
                if (col->unique_id() == uid && col->is_variant_type()) {
1430
167
                    parent = col.get();
1431
167
                    break;
1432
167
                }
1433
524
            }
1434
170
            if (parent == nullptr) {
1435
3
                continue;
1436
3
            }
1437
167
            const int total_buckets = std::max(1, parent->variant_doc_hash_shard_count());
1438
167
            (*doc_path_stats_out)[uid] = segment_v2::VariantDocPathStats::build_from_path_counts(
1439
167
                    info.doc_value_path_total_counts, total_buckets);
1440
167
        }
1441
8.15k
    }
1442
1443
8.17k
    VLOG_DEBUG << "dump schema " << target->dump_full_schema();
1444
8.17k
    return Status::OK();
1445
8.17k
}
1446
1447
// Calculate statistics about variant data paths from the encoded sparse column
1448
void VariantCompactionUtil::calculate_variant_stats(const IColumn& encoded_sparse_column,
1449
                                                    segment_v2::VariantStatisticsPB* stats,
1450
                                                    size_t max_sparse_column_statistics_size,
1451
2.08k
                                                    size_t row_pos, size_t num_rows) {
1452
    // Cast input column to ColumnMap type since sparse column is stored as a map
1453
2.08k
    const auto& map_column = assert_cast<const ColumnMap&>(encoded_sparse_column);
1454
1455
    // Get the keys column which contains the paths as strings
1456
2.08k
    const auto& sparse_data_paths =
1457
2.08k
            assert_cast<const ColumnString*>(map_column.get_keys_ptr().get());
1458
2.08k
    const auto& serialized_sparse_column_offsets = map_column.get_offsets();
1459
2.08k
    auto& count_map = *stats->mutable_sparse_column_non_null_size();
1460
    // Iterate through all paths in the sparse column
1461
745k
    for (size_t i = row_pos; i != row_pos + num_rows; ++i) {
1462
743k
        size_t offset = serialized_sparse_column_offsets[i - 1];
1463
743k
        size_t end = serialized_sparse_column_offsets[i];
1464
2.07M
        for (size_t j = offset; j != end; ++j) {
1465
1.33M
            auto path = sparse_data_paths->get_data_at(j);
1466
1467
1.33M
            const auto& sparse_path = path.to_string();
1468
            // If path already exists in statistics, increment its count
1469
1.33M
            if (auto it = count_map.find(sparse_path); it != count_map.end()) {
1470
1.33M
                ++it->second;
1471
1.33M
            }
1472
            // If path doesn't exist and we haven't hit the max statistics size limit,
1473
            // add it with count 1
1474
4.16k
            else if (count_map.size() < max_sparse_column_statistics_size) {
1475
4.16k
                count_map.emplace(sparse_path, 1);
1476
4.16k
            }
1477
1.33M
        }
1478
743k
    }
1479
1480
2.08k
    if (stats->sparse_column_non_null_size().size() > max_sparse_column_statistics_size) {
1481
0
        throw doris::Exception(
1482
0
                ErrorCode::INTERNAL_ERROR,
1483
0
                "Sparse column non null size: {} is greater than max statistics size: {}",
1484
0
                stats->sparse_column_non_null_size().size(), max_sparse_column_statistics_size);
1485
0
    }
1486
2.08k
}
1487
1488
/// Calculates number of dimensions in array field.
1489
/// Returns 0 for scalar fields.
1490
class FieldVisitorToNumberOfDimensions : public StaticVisitor<size_t> {
1491
public:
1492
    FieldVisitorToNumberOfDimensions() = default;
1493
    template <PrimitiveType T>
1494
21.4M
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1495
21.4M
        if constexpr (T == TYPE_ARRAY) {
1496
991k
            const size_t size = x.size();
1497
991k
            size_t dimensions = 0;
1498
2.90M
            for (size_t i = 0; i < size; ++i) {
1499
1.91M
                size_t element_dimensions = apply_visitor(*this, x[i]);
1500
1.91M
                dimensions = std::max(dimensions, element_dimensions);
1501
1.91M
            }
1502
991k
            return 1 + dimensions;
1503
20.4M
        } else {
1504
20.4M
            return 0;
1505
20.4M
        }
1506
21.4M
    }
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE1EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1494
121k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1495
        if constexpr (T == TYPE_ARRAY) {
1496
            const size_t size = x.size();
1497
            size_t dimensions = 0;
1498
            for (size_t i = 0; i < size; ++i) {
1499
                size_t element_dimensions = apply_visitor(*this, x[i]);
1500
                dimensions = std::max(dimensions, element_dimensions);
1501
            }
1502
            return 1 + dimensions;
1503
121k
        } else {
1504
121k
            return 0;
1505
121k
        }
1506
121k
    }
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE26EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1494
511
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1495
        if constexpr (T == TYPE_ARRAY) {
1496
            const size_t size = x.size();
1497
            size_t dimensions = 0;
1498
            for (size_t i = 0; i < size; ++i) {
1499
                size_t element_dimensions = apply_visitor(*this, x[i]);
1500
                dimensions = std::max(dimensions, element_dimensions);
1501
            }
1502
            return 1 + dimensions;
1503
511
        } else {
1504
511
            return 0;
1505
511
        }
1506
511
    }
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE42EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE7EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1494
41.9k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1495
        if constexpr (T == TYPE_ARRAY) {
1496
            const size_t size = x.size();
1497
            size_t dimensions = 0;
1498
            for (size_t i = 0; i < size; ++i) {
1499
                size_t element_dimensions = apply_visitor(*this, x[i]);
1500
                dimensions = std::max(dimensions, element_dimensions);
1501
            }
1502
            return 1 + dimensions;
1503
41.9k
        } else {
1504
41.9k
            return 0;
1505
41.9k
        }
1506
41.9k
    }
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE12EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE11EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE25EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1494
428
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1495
        if constexpr (T == TYPE_ARRAY) {
1496
            const size_t size = x.size();
1497
            size_t dimensions = 0;
1498
            for (size_t i = 0; i < size; ++i) {
1499
                size_t element_dimensions = apply_visitor(*this, x[i]);
1500
                dimensions = std::max(dimensions, element_dimensions);
1501
            }
1502
            return 1 + dimensions;
1503
428
        } else {
1504
428
            return 0;
1505
428
        }
1506
428
    }
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE2EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1494
332k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1495
        if constexpr (T == TYPE_ARRAY) {
1496
            const size_t size = x.size();
1497
            size_t dimensions = 0;
1498
            for (size_t i = 0; i < size; ++i) {
1499
                size_t element_dimensions = apply_visitor(*this, x[i]);
1500
                dimensions = std::max(dimensions, element_dimensions);
1501
            }
1502
            return 1 + dimensions;
1503
332k
        } else {
1504
332k
            return 0;
1505
332k
        }
1506
332k
    }
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE3EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1494
1.05k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1495
        if constexpr (T == TYPE_ARRAY) {
1496
            const size_t size = x.size();
1497
            size_t dimensions = 0;
1498
            for (size_t i = 0; i < size; ++i) {
1499
                size_t element_dimensions = apply_visitor(*this, x[i]);
1500
                dimensions = std::max(dimensions, element_dimensions);
1501
            }
1502
            return 1 + dimensions;
1503
1.05k
        } else {
1504
1.05k
            return 0;
1505
1.05k
        }
1506
1.05k
    }
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE4EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1494
1.04k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1495
        if constexpr (T == TYPE_ARRAY) {
1496
            const size_t size = x.size();
1497
            size_t dimensions = 0;
1498
            for (size_t i = 0; i < size; ++i) {
1499
                size_t element_dimensions = apply_visitor(*this, x[i]);
1500
                dimensions = std::max(dimensions, element_dimensions);
1501
            }
1502
            return 1 + dimensions;
1503
1.04k
        } else {
1504
1.04k
            return 0;
1505
1.04k
        }
1506
1.04k
    }
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE5EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1494
2.14k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1495
        if constexpr (T == TYPE_ARRAY) {
1496
            const size_t size = x.size();
1497
            size_t dimensions = 0;
1498
            for (size_t i = 0; i < size; ++i) {
1499
                size_t element_dimensions = apply_visitor(*this, x[i]);
1500
                dimensions = std::max(dimensions, element_dimensions);
1501
            }
1502
            return 1 + dimensions;
1503
2.14k
        } else {
1504
2.14k
            return 0;
1505
2.14k
        }
1506
2.14k
    }
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE6EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1494
5.56M
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1495
        if constexpr (T == TYPE_ARRAY) {
1496
            const size_t size = x.size();
1497
            size_t dimensions = 0;
1498
            for (size_t i = 0; i < size; ++i) {
1499
                size_t element_dimensions = apply_visitor(*this, x[i]);
1500
                dimensions = std::max(dimensions, element_dimensions);
1501
            }
1502
            return 1 + dimensions;
1503
5.56M
        } else {
1504
5.56M
            return 0;
1505
5.56M
        }
1506
5.56M
    }
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE38EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE39EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE8EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1494
884
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1495
        if constexpr (T == TYPE_ARRAY) {
1496
            const size_t size = x.size();
1497
            size_t dimensions = 0;
1498
            for (size_t i = 0; i < size; ++i) {
1499
                size_t element_dimensions = apply_visitor(*this, x[i]);
1500
                dimensions = std::max(dimensions, element_dimensions);
1501
            }
1502
            return 1 + dimensions;
1503
884
        } else {
1504
884
            return 0;
1505
884
        }
1506
884
    }
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE27EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE9EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1494
2.96M
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1495
        if constexpr (T == TYPE_ARRAY) {
1496
            const size_t size = x.size();
1497
            size_t dimensions = 0;
1498
            for (size_t i = 0; i < size; ++i) {
1499
                size_t element_dimensions = apply_visitor(*this, x[i]);
1500
                dimensions = std::max(dimensions, element_dimensions);
1501
            }
1502
            return 1 + dimensions;
1503
2.96M
        } else {
1504
2.96M
            return 0;
1505
2.96M
        }
1506
2.96M
    }
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE36EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1494
339
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1495
        if constexpr (T == TYPE_ARRAY) {
1496
            const size_t size = x.size();
1497
            size_t dimensions = 0;
1498
            for (size_t i = 0; i < size; ++i) {
1499
                size_t element_dimensions = apply_visitor(*this, x[i]);
1500
                dimensions = std::max(dimensions, element_dimensions);
1501
            }
1502
            return 1 + dimensions;
1503
339
        } else {
1504
339
            return 0;
1505
339
        }
1506
339
    }
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE37EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1494
338
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1495
        if constexpr (T == TYPE_ARRAY) {
1496
            const size_t size = x.size();
1497
            size_t dimensions = 0;
1498
            for (size_t i = 0; i < size; ++i) {
1499
                size_t element_dimensions = apply_visitor(*this, x[i]);
1500
                dimensions = std::max(dimensions, element_dimensions);
1501
            }
1502
            return 1 + dimensions;
1503
338
        } else {
1504
338
            return 0;
1505
338
        }
1506
338
    }
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE23EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1494
11.3M
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1495
        if constexpr (T == TYPE_ARRAY) {
1496
            const size_t size = x.size();
1497
            size_t dimensions = 0;
1498
            for (size_t i = 0; i < size; ++i) {
1499
                size_t element_dimensions = apply_visitor(*this, x[i]);
1500
                dimensions = std::max(dimensions, element_dimensions);
1501
            }
1502
            return 1 + dimensions;
1503
11.3M
        } else {
1504
11.3M
            return 0;
1505
11.3M
        }
1506
11.3M
    }
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE15EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE10EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE41EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE17EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1494
991k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1495
991k
        if constexpr (T == TYPE_ARRAY) {
1496
991k
            const size_t size = x.size();
1497
991k
            size_t dimensions = 0;
1498
2.90M
            for (size_t i = 0; i < size; ++i) {
1499
1.91M
                size_t element_dimensions = apply_visitor(*this, x[i]);
1500
1.91M
                dimensions = std::max(dimensions, element_dimensions);
1501
1.91M
            }
1502
991k
            return 1 + dimensions;
1503
        } else {
1504
            return 0;
1505
        }
1506
991k
    }
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE16EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1494
1
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1495
        if constexpr (T == TYPE_ARRAY) {
1496
            const size_t size = x.size();
1497
            size_t dimensions = 0;
1498
            for (size_t i = 0; i < size; ++i) {
1499
                size_t element_dimensions = apply_visitor(*this, x[i]);
1500
                dimensions = std::max(dimensions, element_dimensions);
1501
            }
1502
            return 1 + dimensions;
1503
1
        } else {
1504
1
            return 0;
1505
1
        }
1506
1
    }
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE18EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE32EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1494
1
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1495
        if constexpr (T == TYPE_ARRAY) {
1496
            const size_t size = x.size();
1497
            size_t dimensions = 0;
1498
            for (size_t i = 0; i < size; ++i) {
1499
                size_t element_dimensions = apply_visitor(*this, x[i]);
1500
                dimensions = std::max(dimensions, element_dimensions);
1501
            }
1502
            return 1 + dimensions;
1503
1
        } else {
1504
1
            return 0;
1505
1
        }
1506
1
    }
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE28EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1494
783
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1495
        if constexpr (T == TYPE_ARRAY) {
1496
            const size_t size = x.size();
1497
            size_t dimensions = 0;
1498
            for (size_t i = 0; i < size; ++i) {
1499
                size_t element_dimensions = apply_visitor(*this, x[i]);
1500
                dimensions = std::max(dimensions, element_dimensions);
1501
            }
1502
            return 1 + dimensions;
1503
783
        } else {
1504
783
            return 0;
1505
783
        }
1506
783
    }
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE29EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1494
724
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1495
        if constexpr (T == TYPE_ARRAY) {
1496
            const size_t size = x.size();
1497
            size_t dimensions = 0;
1498
            for (size_t i = 0; i < size; ++i) {
1499
                size_t element_dimensions = apply_visitor(*this, x[i]);
1500
                dimensions = std::max(dimensions, element_dimensions);
1501
            }
1502
            return 1 + dimensions;
1503
724
        } else {
1504
724
            return 0;
1505
724
        }
1506
724
    }
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE20EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE30EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1494
70.8k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1495
        if constexpr (T == TYPE_ARRAY) {
1496
            const size_t size = x.size();
1497
            size_t dimensions = 0;
1498
            for (size_t i = 0; i < size; ++i) {
1499
                size_t element_dimensions = apply_visitor(*this, x[i]);
1500
                dimensions = std::max(dimensions, element_dimensions);
1501
            }
1502
            return 1 + dimensions;
1503
70.8k
        } else {
1504
70.8k
            return 0;
1505
70.8k
        }
1506
70.8k
    }
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE35EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1494
588
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1495
        if constexpr (T == TYPE_ARRAY) {
1496
            const size_t size = x.size();
1497
            size_t dimensions = 0;
1498
            for (size_t i = 0; i < size; ++i) {
1499
                size_t element_dimensions = apply_visitor(*this, x[i]);
1500
                dimensions = std::max(dimensions, element_dimensions);
1501
            }
1502
            return 1 + dimensions;
1503
588
        } else {
1504
588
            return 0;
1505
588
        }
1506
588
    }
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE22EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE19EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE24EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util32FieldVisitorToNumberOfDimensions5applyILNS_13PrimitiveTypeE31EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1494
46.9k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1495
        if constexpr (T == TYPE_ARRAY) {
1496
            const size_t size = x.size();
1497
            size_t dimensions = 0;
1498
            for (size_t i = 0; i < size; ++i) {
1499
                size_t element_dimensions = apply_visitor(*this, x[i]);
1500
                dimensions = std::max(dimensions, element_dimensions);
1501
            }
1502
            return 1 + dimensions;
1503
46.9k
        } else {
1504
46.9k
            return 0;
1505
46.9k
        }
1506
46.9k
    }
1507
};
1508
1509
// Visitor that allows to get type of scalar field
1510
// but exclude fields contain complex field.This is a faster version
1511
// for FieldVisitorToScalarType which does not support complex field.
1512
class SimpleFieldVisitorToScalarType : public StaticVisitor<size_t> {
1513
public:
1514
    template <PrimitiveType T>
1515
18.8M
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1516
18.8M
        if constexpr (T == TYPE_ARRAY) {
1517
0
            throw doris::Exception(ErrorCode::INVALID_ARGUMENT, "Array type is not supported");
1518
109k
        } else if constexpr (T == TYPE_NULL) {
1519
109k
            have_nulls = true;
1520
109k
            return 1;
1521
18.7M
        } else {
1522
18.7M
            type = T;
1523
18.7M
            return 1;
1524
18.7M
        }
1525
18.8M
    }
_ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE1EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1515
109k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1516
        if constexpr (T == TYPE_ARRAY) {
1517
            throw doris::Exception(ErrorCode::INVALID_ARGUMENT, "Array type is not supported");
1518
109k
        } else if constexpr (T == TYPE_NULL) {
1519
109k
            have_nulls = true;
1520
109k
            return 1;
1521
        } else {
1522
            type = T;
1523
            return 1;
1524
        }
1525
109k
    }
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE26EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE42EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE7EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1515
12.3k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1516
        if constexpr (T == TYPE_ARRAY) {
1517
            throw doris::Exception(ErrorCode::INVALID_ARGUMENT, "Array type is not supported");
1518
        } else if constexpr (T == TYPE_NULL) {
1519
            have_nulls = true;
1520
            return 1;
1521
12.3k
        } else {
1522
12.3k
            type = T;
1523
12.3k
            return 1;
1524
12.3k
        }
1525
12.3k
    }
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE12EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE11EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE25EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE2EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1515
273k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1516
        if constexpr (T == TYPE_ARRAY) {
1517
            throw doris::Exception(ErrorCode::INVALID_ARGUMENT, "Array type is not supported");
1518
        } else if constexpr (T == TYPE_NULL) {
1519
            have_nulls = true;
1520
            return 1;
1521
273k
        } else {
1522
273k
            type = T;
1523
273k
            return 1;
1524
273k
        }
1525
273k
    }
_ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE3EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1515
2
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1516
        if constexpr (T == TYPE_ARRAY) {
1517
            throw doris::Exception(ErrorCode::INVALID_ARGUMENT, "Array type is not supported");
1518
        } else if constexpr (T == TYPE_NULL) {
1519
            have_nulls = true;
1520
            return 1;
1521
2
        } else {
1522
2
            type = T;
1523
2
            return 1;
1524
2
        }
1525
2
    }
_ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE4EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1515
7
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1516
        if constexpr (T == TYPE_ARRAY) {
1517
            throw doris::Exception(ErrorCode::INVALID_ARGUMENT, "Array type is not supported");
1518
        } else if constexpr (T == TYPE_NULL) {
1519
            have_nulls = true;
1520
            return 1;
1521
7
        } else {
1522
7
            type = T;
1523
7
            return 1;
1524
7
        }
1525
7
    }
_ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE5EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1515
735
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1516
        if constexpr (T == TYPE_ARRAY) {
1517
            throw doris::Exception(ErrorCode::INVALID_ARGUMENT, "Array type is not supported");
1518
        } else if constexpr (T == TYPE_NULL) {
1519
            have_nulls = true;
1520
            return 1;
1521
735
        } else {
1522
735
            type = T;
1523
735
            return 1;
1524
735
        }
1525
735
    }
_ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE6EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1515
5.03M
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1516
        if constexpr (T == TYPE_ARRAY) {
1517
            throw doris::Exception(ErrorCode::INVALID_ARGUMENT, "Array type is not supported");
1518
        } else if constexpr (T == TYPE_NULL) {
1519
            have_nulls = true;
1520
            return 1;
1521
5.03M
        } else {
1522
5.03M
            type = T;
1523
5.03M
            return 1;
1524
5.03M
        }
1525
5.03M
    }
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE38EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE39EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE8EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1515
1
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1516
        if constexpr (T == TYPE_ARRAY) {
1517
            throw doris::Exception(ErrorCode::INVALID_ARGUMENT, "Array type is not supported");
1518
        } else if constexpr (T == TYPE_NULL) {
1519
            have_nulls = true;
1520
            return 1;
1521
1
        } else {
1522
1
            type = T;
1523
1
            return 1;
1524
1
        }
1525
1
    }
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE27EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE9EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1515
2.76M
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1516
        if constexpr (T == TYPE_ARRAY) {
1517
            throw doris::Exception(ErrorCode::INVALID_ARGUMENT, "Array type is not supported");
1518
        } else if constexpr (T == TYPE_NULL) {
1519
            have_nulls = true;
1520
            return 1;
1521
2.76M
        } else {
1522
2.76M
            type = T;
1523
2.76M
            return 1;
1524
2.76M
        }
1525
2.76M
    }
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE36EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE37EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE23EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1515
10.5M
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1516
        if constexpr (T == TYPE_ARRAY) {
1517
            throw doris::Exception(ErrorCode::INVALID_ARGUMENT, "Array type is not supported");
1518
        } else if constexpr (T == TYPE_NULL) {
1519
            have_nulls = true;
1520
            return 1;
1521
10.5M
        } else {
1522
10.5M
            type = T;
1523
10.5M
            return 1;
1524
10.5M
        }
1525
10.5M
    }
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE15EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE10EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE41EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE17EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE16EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE18EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE32EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE28EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE29EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE20EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE30EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE35EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE22EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE19EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE24EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util30SimpleFieldVisitorToScalarType5applyILNS_13PrimitiveTypeE31EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1515
46.8k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1516
        if constexpr (T == TYPE_ARRAY) {
1517
            throw doris::Exception(ErrorCode::INVALID_ARGUMENT, "Array type is not supported");
1518
        } else if constexpr (T == TYPE_NULL) {
1519
            have_nulls = true;
1520
            return 1;
1521
46.8k
        } else {
1522
46.8k
            type = T;
1523
46.8k
            return 1;
1524
46.8k
        }
1525
46.8k
    }
1526
18.4M
    void get_scalar_type(PrimitiveType* data_type) const { *data_type = type; }
1527
18.5M
    bool contain_nulls() const { return have_nulls; }
1528
1529
18.5M
    bool need_convert_field() const { return false; }
1530
1531
private:
1532
    PrimitiveType type = PrimitiveType::INVALID_TYPE;
1533
    bool have_nulls = false;
1534
};
1535
1536
/// Visitor that allows to get type of scalar field
1537
/// or least common type of scalars in array.
1538
/// More optimized version of FieldToDataType.
1539
class FieldVisitorToScalarType : public StaticVisitor<size_t> {
1540
public:
1541
    template <PrimitiveType T>
1542
2.69M
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1543
2.69M
        if constexpr (T == TYPE_ARRAY) {
1544
992k
            size_t size = x.size();
1545
2.90M
            for (size_t i = 0; i < size; ++i) {
1546
1.91M
                apply_visitor(*this, x[i]);
1547
1.91M
            }
1548
992k
            return 0;
1549
992k
        } else if constexpr (T == TYPE_NULL) {
1550
12.2k
            have_nulls = true;
1551
12.2k
            return 0;
1552
1.68M
        } else {
1553
1.68M
            field_types.insert(T);
1554
1.68M
            type_indexes.insert(T);
1555
1.68M
            return 0;
1556
1.68M
        }
1557
2.69M
    }
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE1EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1542
12.2k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1543
        if constexpr (T == TYPE_ARRAY) {
1544
            size_t size = x.size();
1545
            for (size_t i = 0; i < size; ++i) {
1546
                apply_visitor(*this, x[i]);
1547
            }
1548
            return 0;
1549
12.2k
        } else if constexpr (T == TYPE_NULL) {
1550
12.2k
            have_nulls = true;
1551
12.2k
            return 0;
1552
        } else {
1553
            field_types.insert(T);
1554
            type_indexes.insert(T);
1555
            return 0;
1556
        }
1557
12.2k
    }
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE26EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1542
511
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1543
        if constexpr (T == TYPE_ARRAY) {
1544
            size_t size = x.size();
1545
            for (size_t i = 0; i < size; ++i) {
1546
                apply_visitor(*this, x[i]);
1547
            }
1548
            return 0;
1549
        } else if constexpr (T == TYPE_NULL) {
1550
            have_nulls = true;
1551
            return 0;
1552
511
        } else {
1553
511
            field_types.insert(T);
1554
511
            type_indexes.insert(T);
1555
511
            return 0;
1556
511
        }
1557
511
    }
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE42EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE7EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1542
29.6k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1543
        if constexpr (T == TYPE_ARRAY) {
1544
            size_t size = x.size();
1545
            for (size_t i = 0; i < size; ++i) {
1546
                apply_visitor(*this, x[i]);
1547
            }
1548
            return 0;
1549
        } else if constexpr (T == TYPE_NULL) {
1550
            have_nulls = true;
1551
            return 0;
1552
29.6k
        } else {
1553
29.6k
            field_types.insert(T);
1554
29.6k
            type_indexes.insert(T);
1555
29.6k
            return 0;
1556
29.6k
        }
1557
29.6k
    }
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE12EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE11EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE25EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1542
428
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1543
        if constexpr (T == TYPE_ARRAY) {
1544
            size_t size = x.size();
1545
            for (size_t i = 0; i < size; ++i) {
1546
                apply_visitor(*this, x[i]);
1547
            }
1548
            return 0;
1549
        } else if constexpr (T == TYPE_NULL) {
1550
            have_nulls = true;
1551
            return 0;
1552
428
        } else {
1553
428
            field_types.insert(T);
1554
428
            type_indexes.insert(T);
1555
428
            return 0;
1556
428
        }
1557
428
    }
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE2EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1542
58.3k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1543
        if constexpr (T == TYPE_ARRAY) {
1544
            size_t size = x.size();
1545
            for (size_t i = 0; i < size; ++i) {
1546
                apply_visitor(*this, x[i]);
1547
            }
1548
            return 0;
1549
        } else if constexpr (T == TYPE_NULL) {
1550
            have_nulls = true;
1551
            return 0;
1552
58.3k
        } else {
1553
58.3k
            field_types.insert(T);
1554
58.3k
            type_indexes.insert(T);
1555
58.3k
            return 0;
1556
58.3k
        }
1557
58.3k
    }
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE3EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1542
1.04k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1543
        if constexpr (T == TYPE_ARRAY) {
1544
            size_t size = x.size();
1545
            for (size_t i = 0; i < size; ++i) {
1546
                apply_visitor(*this, x[i]);
1547
            }
1548
            return 0;
1549
        } else if constexpr (T == TYPE_NULL) {
1550
            have_nulls = true;
1551
            return 0;
1552
1.04k
        } else {
1553
1.04k
            field_types.insert(T);
1554
1.04k
            type_indexes.insert(T);
1555
1.04k
            return 0;
1556
1.04k
        }
1557
1.04k
    }
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE4EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1542
1.03k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1543
        if constexpr (T == TYPE_ARRAY) {
1544
            size_t size = x.size();
1545
            for (size_t i = 0; i < size; ++i) {
1546
                apply_visitor(*this, x[i]);
1547
            }
1548
            return 0;
1549
        } else if constexpr (T == TYPE_NULL) {
1550
            have_nulls = true;
1551
            return 0;
1552
1.03k
        } else {
1553
1.03k
            field_types.insert(T);
1554
1.03k
            type_indexes.insert(T);
1555
1.03k
            return 0;
1556
1.03k
        }
1557
1.03k
    }
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE5EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1542
1.40k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1543
        if constexpr (T == TYPE_ARRAY) {
1544
            size_t size = x.size();
1545
            for (size_t i = 0; i < size; ++i) {
1546
                apply_visitor(*this, x[i]);
1547
            }
1548
            return 0;
1549
        } else if constexpr (T == TYPE_NULL) {
1550
            have_nulls = true;
1551
            return 0;
1552
1.40k
        } else {
1553
1.40k
            field_types.insert(T);
1554
1.40k
            type_indexes.insert(T);
1555
1.40k
            return 0;
1556
1.40k
        }
1557
1.40k
    }
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE6EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1542
547k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1543
        if constexpr (T == TYPE_ARRAY) {
1544
            size_t size = x.size();
1545
            for (size_t i = 0; i < size; ++i) {
1546
                apply_visitor(*this, x[i]);
1547
            }
1548
            return 0;
1549
        } else if constexpr (T == TYPE_NULL) {
1550
            have_nulls = true;
1551
            return 0;
1552
547k
        } else {
1553
547k
            field_types.insert(T);
1554
547k
            type_indexes.insert(T);
1555
547k
            return 0;
1556
547k
        }
1557
547k
    }
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE38EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE39EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE8EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1542
883
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1543
        if constexpr (T == TYPE_ARRAY) {
1544
            size_t size = x.size();
1545
            for (size_t i = 0; i < size; ++i) {
1546
                apply_visitor(*this, x[i]);
1547
            }
1548
            return 0;
1549
        } else if constexpr (T == TYPE_NULL) {
1550
            have_nulls = true;
1551
            return 0;
1552
883
        } else {
1553
883
            field_types.insert(T);
1554
883
            type_indexes.insert(T);
1555
883
            return 0;
1556
883
        }
1557
883
    }
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE27EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE9EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1542
197k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1543
        if constexpr (T == TYPE_ARRAY) {
1544
            size_t size = x.size();
1545
            for (size_t i = 0; i < size; ++i) {
1546
                apply_visitor(*this, x[i]);
1547
            }
1548
            return 0;
1549
        } else if constexpr (T == TYPE_NULL) {
1550
            have_nulls = true;
1551
            return 0;
1552
197k
        } else {
1553
197k
            field_types.insert(T);
1554
197k
            type_indexes.insert(T);
1555
197k
            return 0;
1556
197k
        }
1557
197k
    }
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE36EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1542
339
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1543
        if constexpr (T == TYPE_ARRAY) {
1544
            size_t size = x.size();
1545
            for (size_t i = 0; i < size; ++i) {
1546
                apply_visitor(*this, x[i]);
1547
            }
1548
            return 0;
1549
        } else if constexpr (T == TYPE_NULL) {
1550
            have_nulls = true;
1551
            return 0;
1552
339
        } else {
1553
339
            field_types.insert(T);
1554
339
            type_indexes.insert(T);
1555
339
            return 0;
1556
339
        }
1557
339
    }
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE37EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1542
338
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1543
        if constexpr (T == TYPE_ARRAY) {
1544
            size_t size = x.size();
1545
            for (size_t i = 0; i < size; ++i) {
1546
                apply_visitor(*this, x[i]);
1547
            }
1548
            return 0;
1549
        } else if constexpr (T == TYPE_NULL) {
1550
            have_nulls = true;
1551
            return 0;
1552
338
        } else {
1553
338
            field_types.insert(T);
1554
338
            type_indexes.insert(T);
1555
338
            return 0;
1556
338
        }
1557
338
    }
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE23EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1542
777k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1543
        if constexpr (T == TYPE_ARRAY) {
1544
            size_t size = x.size();
1545
            for (size_t i = 0; i < size; ++i) {
1546
                apply_visitor(*this, x[i]);
1547
            }
1548
            return 0;
1549
        } else if constexpr (T == TYPE_NULL) {
1550
            have_nulls = true;
1551
            return 0;
1552
777k
        } else {
1553
777k
            field_types.insert(T);
1554
777k
            type_indexes.insert(T);
1555
777k
            return 0;
1556
777k
        }
1557
777k
    }
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE15EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE10EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE41EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE17EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1542
992k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1543
992k
        if constexpr (T == TYPE_ARRAY) {
1544
992k
            size_t size = x.size();
1545
2.90M
            for (size_t i = 0; i < size; ++i) {
1546
1.91M
                apply_visitor(*this, x[i]);
1547
1.91M
            }
1548
992k
            return 0;
1549
        } else if constexpr (T == TYPE_NULL) {
1550
            have_nulls = true;
1551
            return 0;
1552
        } else {
1553
            field_types.insert(T);
1554
            type_indexes.insert(T);
1555
            return 0;
1556
        }
1557
992k
    }
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE16EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1542
1
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1543
        if constexpr (T == TYPE_ARRAY) {
1544
            size_t size = x.size();
1545
            for (size_t i = 0; i < size; ++i) {
1546
                apply_visitor(*this, x[i]);
1547
            }
1548
            return 0;
1549
        } else if constexpr (T == TYPE_NULL) {
1550
            have_nulls = true;
1551
            return 0;
1552
1
        } else {
1553
1
            field_types.insert(T);
1554
1
            type_indexes.insert(T);
1555
1
            return 0;
1556
1
        }
1557
1
    }
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE18EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE32EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1542
1
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1543
        if constexpr (T == TYPE_ARRAY) {
1544
            size_t size = x.size();
1545
            for (size_t i = 0; i < size; ++i) {
1546
                apply_visitor(*this, x[i]);
1547
            }
1548
            return 0;
1549
        } else if constexpr (T == TYPE_NULL) {
1550
            have_nulls = true;
1551
            return 0;
1552
1
        } else {
1553
1
            field_types.insert(T);
1554
1
            type_indexes.insert(T);
1555
1
            return 0;
1556
1
        }
1557
1
    }
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE28EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1542
783
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1543
        if constexpr (T == TYPE_ARRAY) {
1544
            size_t size = x.size();
1545
            for (size_t i = 0; i < size; ++i) {
1546
                apply_visitor(*this, x[i]);
1547
            }
1548
            return 0;
1549
        } else if constexpr (T == TYPE_NULL) {
1550
            have_nulls = true;
1551
            return 0;
1552
783
        } else {
1553
783
            field_types.insert(T);
1554
783
            type_indexes.insert(T);
1555
783
            return 0;
1556
783
        }
1557
783
    }
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE29EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1542
724
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1543
        if constexpr (T == TYPE_ARRAY) {
1544
            size_t size = x.size();
1545
            for (size_t i = 0; i < size; ++i) {
1546
                apply_visitor(*this, x[i]);
1547
            }
1548
            return 0;
1549
        } else if constexpr (T == TYPE_NULL) {
1550
            have_nulls = true;
1551
            return 0;
1552
724
        } else {
1553
724
            field_types.insert(T);
1554
724
            type_indexes.insert(T);
1555
724
            return 0;
1556
724
        }
1557
724
    }
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE20EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE30EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1542
70.8k
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1543
        if constexpr (T == TYPE_ARRAY) {
1544
            size_t size = x.size();
1545
            for (size_t i = 0; i < size; ++i) {
1546
                apply_visitor(*this, x[i]);
1547
            }
1548
            return 0;
1549
        } else if constexpr (T == TYPE_NULL) {
1550
            have_nulls = true;
1551
            return 0;
1552
70.8k
        } else {
1553
70.8k
            field_types.insert(T);
1554
70.8k
            type_indexes.insert(T);
1555
70.8k
            return 0;
1556
70.8k
        }
1557
70.8k
    }
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE35EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1542
588
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1543
        if constexpr (T == TYPE_ARRAY) {
1544
            size_t size = x.size();
1545
            for (size_t i = 0; i < size; ++i) {
1546
                apply_visitor(*this, x[i]);
1547
            }
1548
            return 0;
1549
        } else if constexpr (T == TYPE_NULL) {
1550
            have_nulls = true;
1551
            return 0;
1552
588
        } else {
1553
588
            field_types.insert(T);
1554
588
            type_indexes.insert(T);
1555
588
            return 0;
1556
588
        }
1557
588
    }
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE22EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE19EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Unexecuted instantiation: _ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE24EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
_ZN5doris12variant_util24FieldVisitorToScalarType5applyILNS_13PrimitiveTypeE31EEEmRKNS_19PrimitiveTypeTraitsIXT_EE7CppTypeE
Line
Count
Source
1542
44
    size_t apply(const typename PrimitiveTypeTraits<T>::CppType& x) {
1543
        if constexpr (T == TYPE_ARRAY) {
1544
            size_t size = x.size();
1545
            for (size_t i = 0; i < size; ++i) {
1546
                apply_visitor(*this, x[i]);
1547
            }
1548
            return 0;
1549
        } else if constexpr (T == TYPE_NULL) {
1550
            have_nulls = true;
1551
            return 0;
1552
44
        } else {
1553
44
            field_types.insert(T);
1554
44
            type_indexes.insert(T);
1555
44
            return 0;
1556
44
        }
1557
44
    }
1558
778k
    void get_scalar_type(PrimitiveType* type) const {
1559
778k
        if (type_indexes.size() == 1) {
1560
            // Most cases will have only one type
1561
704k
            *type = *type_indexes.begin();
1562
704k
            return;
1563
704k
        }
1564
74.1k
        DataTypePtr data_type;
1565
74.1k
        get_least_supertype_jsonb(type_indexes, &data_type);
1566
74.1k
        *type = data_type->get_primitive_type();
1567
74.1k
    }
1568
778k
    bool contain_nulls() const { return have_nulls; }
1569
778k
    bool need_convert_field() const { return field_types.size() > 1; }
1570
1571
private:
1572
    phmap::flat_hash_set<PrimitiveType> type_indexes;
1573
    phmap::flat_hash_set<PrimitiveType> field_types;
1574
    bool have_nulls = false;
1575
};
1576
1577
template <typename Visitor>
1578
19.6M
void get_field_info_impl(const Field& field, FieldInfo* info) {
1579
19.6M
    Visitor to_scalar_type_visitor;
1580
19.6M
    apply_visitor(to_scalar_type_visitor, field);
1581
19.6M
    PrimitiveType type_id;
1582
19.6M
    to_scalar_type_visitor.get_scalar_type(&type_id);
1583
    // array item's dimension may missmatch, eg. [1, 2, [1, 2, 3]]
1584
19.6M
    *info = {type_id, to_scalar_type_visitor.contain_nulls(),
1585
19.6M
             to_scalar_type_visitor.need_convert_field(),
1586
19.6M
             apply_visitor(FieldVisitorToNumberOfDimensions(), field)};
1587
19.6M
}
_ZN5doris12variant_util19get_field_info_implINS0_24FieldVisitorToScalarTypeEEEvRKNS_5FieldEPNS_9FieldInfoE
Line
Count
Source
1578
778k
void get_field_info_impl(const Field& field, FieldInfo* info) {
1579
778k
    Visitor to_scalar_type_visitor;
1580
778k
    apply_visitor(to_scalar_type_visitor, field);
1581
778k
    PrimitiveType type_id;
1582
778k
    to_scalar_type_visitor.get_scalar_type(&type_id);
1583
    // array item's dimension may missmatch, eg. [1, 2, [1, 2, 3]]
1584
778k
    *info = {type_id, to_scalar_type_visitor.contain_nulls(),
1585
778k
             to_scalar_type_visitor.need_convert_field(),
1586
778k
             apply_visitor(FieldVisitorToNumberOfDimensions(), field)};
1587
778k
}
_ZN5doris12variant_util19get_field_info_implINS0_30SimpleFieldVisitorToScalarTypeEEEvRKNS_5FieldEPNS_9FieldInfoE
Line
Count
Source
1578
18.8M
void get_field_info_impl(const Field& field, FieldInfo* info) {
1579
18.8M
    Visitor to_scalar_type_visitor;
1580
18.8M
    apply_visitor(to_scalar_type_visitor, field);
1581
18.8M
    PrimitiveType type_id;
1582
18.8M
    to_scalar_type_visitor.get_scalar_type(&type_id);
1583
    // array item's dimension may missmatch, eg. [1, 2, [1, 2, 3]]
1584
18.8M
    *info = {type_id, to_scalar_type_visitor.contain_nulls(),
1585
18.8M
             to_scalar_type_visitor.need_convert_field(),
1586
18.8M
             apply_visitor(FieldVisitorToNumberOfDimensions(), field)};
1587
18.8M
}
1588
1589
19.6M
void get_field_info(const Field& field, FieldInfo* info) {
1590
19.6M
    if (field.is_complex_field()) {
1591
779k
        get_field_info_impl<FieldVisitorToScalarType>(field, info);
1592
18.8M
    } else {
1593
18.8M
        get_field_info_impl<SimpleFieldVisitorToScalarType>(field, info);
1594
18.8M
    }
1595
19.6M
}
1596
1597
bool generate_sub_column_info(const TabletSchema& schema, int32_t col_unique_id,
1598
                              const std::string& path,
1599
231k
                              TabletSchema::SubColumnInfo* sub_column_info) {
1600
231k
    const auto& parent_column = schema.column_by_uid(col_unique_id);
1601
231k
    std::function<void(const TabletColumn&, TabletColumn*)> generate_result_column =
1602
231k
            [&](const TabletColumn& from_column, TabletColumn* to_column) {
1603
13.8k
                to_column->set_name(parent_column.name_lower_case() + "." + path);
1604
13.8k
                to_column->set_type(from_column.type());
1605
13.8k
                to_column->set_parent_unique_id(parent_column.unique_id());
1606
13.8k
                bool is_typed = !parent_column.variant_enable_typed_paths_to_sparse();
1607
13.8k
                to_column->set_path_info(
1608
13.8k
                        PathInData(parent_column.name_lower_case() + "." + path, is_typed));
1609
13.8k
                to_column->set_aggregation_method(parent_column.aggregation());
1610
13.8k
                to_column->set_is_nullable(true);
1611
13.8k
                to_column->set_parent_unique_id(parent_column.unique_id());
1612
13.8k
                if (from_column.is_decimal()) {
1613
13.6k
                    to_column->set_precision(from_column.precision());
1614
13.6k
                }
1615
13.8k
                to_column->set_frac(from_column.frac());
1616
1617
13.8k
                if (from_column.is_array_type()) {
1618
3.30k
                    TabletColumn nested_column;
1619
3.30k
                    generate_result_column(*from_column.get_sub_columns()[0], &nested_column);
1620
3.30k
                    to_column->add_sub_column(nested_column);
1621
3.30k
                }
1622
13.8k
            };
1623
1624
231k
    auto generate_index = [&](const std::string& pattern) {
1625
        // 1. find subcolumn's index
1626
10.5k
        if (const auto& indexes = schema.inverted_index_by_field_pattern(col_unique_id, pattern);
1627
10.5k
            !indexes.empty()) {
1628
4.48k
            for (const auto& index : indexes) {
1629
4.48k
                auto index_ptr = std::make_shared<TabletIndex>(*index);
1630
4.48k
                index_ptr->set_escaped_escaped_index_suffix_path(
1631
4.48k
                        sub_column_info->column.path_info_ptr()->get_path());
1632
4.48k
                sub_column_info->indexes.emplace_back(std::move(index_ptr));
1633
4.48k
            }
1634
4.41k
        }
1635
        // 2. find parent column's index
1636
6.08k
        else if (const auto parent_index = schema.inverted_indexs(col_unique_id);
1637
6.08k
                 !parent_index.empty()) {
1638
454
            inherit_index(parent_index, sub_column_info->indexes, sub_column_info->column);
1639
5.63k
        } else {
1640
5.63k
            sub_column_info->indexes.clear();
1641
5.63k
        }
1642
10.5k
    };
1643
1644
231k
    const auto& sub_columns = parent_column.get_sub_columns();
1645
231k
    for (const auto& sub_column : sub_columns) {
1646
166k
        const char* pattern = sub_column->name().c_str();
1647
166k
        switch (sub_column->pattern_type()) {
1648
5.77k
        case PatternTypePB::MATCH_NAME: {
1649
5.77k
            if (strcmp(pattern, path.c_str()) == 0) {
1650
1.89k
                generate_result_column(*sub_column, &sub_column_info->column);
1651
1.89k
                generate_index(sub_column->name());
1652
1.89k
                return true;
1653
1.89k
            }
1654
3.88k
            break;
1655
5.77k
        }
1656
161k
        case PatternTypePB::MATCH_NAME_GLOB: {
1657
161k
            if (glob_match_re2(pattern, path)) {
1658
8.61k
                generate_result_column(*sub_column, &sub_column_info->column);
1659
8.61k
                generate_index(sub_column->name());
1660
8.61k
                return true;
1661
8.61k
            }
1662
152k
            break;
1663
161k
        }
1664
152k
        default:
1665
0
            break;
1666
166k
        }
1667
166k
    }
1668
220k
    return false;
1669
231k
}
1670
1671
TabletSchemaSPtr VariantCompactionUtil::calculate_variant_extended_schema(
1672
1.41k
        const std::vector<RowsetSharedPtr>& rowsets, const TabletSchemaSPtr& base_schema) {
1673
1.41k
    if (rowsets.empty()) {
1674
0
        return nullptr;
1675
0
    }
1676
1677
1.41k
    std::vector<TabletSchemaSPtr> schemas;
1678
3.31k
    for (const auto& rs : rowsets) {
1679
3.31k
        if (rs->num_segments() == 0) {
1680
3.14k
            continue;
1681
3.14k
        }
1682
172
        const auto& tablet_schema = rs->tablet_schema();
1683
172
        SegmentCacheHandle segment_cache;
1684
172
        auto st = SegmentLoader::instance()->load_segments(std::static_pointer_cast<BetaRowset>(rs),
1685
172
                                                           &segment_cache);
1686
172
        if (!st.ok()) {
1687
0
            return base_schema;
1688
0
        }
1689
172
        for (const auto& segment : segment_cache.get_segments()) {
1690
172
            TabletSchemaSPtr schema = tablet_schema->copy_without_variant_extracted_columns();
1691
350
            for (const auto& column : tablet_schema->columns()) {
1692
350
                if (!column->is_variant_type()) {
1693
172
                    continue;
1694
172
                }
1695
178
                std::shared_ptr<ColumnReader> column_reader;
1696
178
                OlapReaderStatistics stats;
1697
178
                st = segment->get_column_reader(column->unique_id(), &column_reader, &stats);
1698
178
                if (!st.ok()) {
1699
0
                    LOG(WARNING) << "Failed to get column reader for column: " << column->name()
1700
0
                                 << " error: " << st.to_string();
1701
0
                    continue;
1702
0
                }
1703
178
                if (!column_reader) {
1704
0
                    continue;
1705
0
                }
1706
1707
178
                CHECK(column_reader->get_meta_type() == FieldType::OLAP_FIELD_TYPE_VARIANT);
1708
178
                auto* variant_column_reader =
1709
178
                        assert_cast<segment_v2::VariantColumnReader*>(column_reader.get());
1710
                // load external meta before getting subcolumn meta info
1711
178
                st = variant_column_reader->load_external_meta_once();
1712
178
                if (!st.ok()) {
1713
0
                    LOG(WARNING) << "Failed to load external meta for column: " << column->name()
1714
0
                                 << " error: " << st.to_string();
1715
0
                    continue;
1716
0
                }
1717
178
                const auto* subcolumn_meta_info = variant_column_reader->get_subcolumns_meta_info();
1718
509
                for (const auto& entry : *subcolumn_meta_info) {
1719
509
                    if (entry->path.empty()) {
1720
178
                        continue;
1721
178
                    }
1722
331
                    const std::string& column_name =
1723
331
                            column->name_lower_case() + "." + entry->path.get_path();
1724
331
                    const DataTypePtr& data_type = entry->data.file_column_type;
1725
331
                    PathInDataBuilder full_path_builder;
1726
331
                    auto full_path = full_path_builder.append(column->name_lower_case(), false)
1727
331
                                             .append(entry->path.get_parts(), false)
1728
331
                                             .build();
1729
331
                    TabletColumn subcolumn =
1730
331
                            get_column_by_type(data_type, column_name,
1731
331
                                               ExtraInfo {.unique_id = -1,
1732
331
                                                          .parent_unique_id = column->unique_id(),
1733
331
                                                          .path_info = full_path});
1734
331
                    schema->append_column(subcolumn);
1735
331
                }
1736
178
            }
1737
172
            schemas.emplace_back(schema);
1738
172
        }
1739
172
    }
1740
1.41k
    TabletSchemaSPtr least_common_schema;
1741
1.41k
    auto st = get_least_common_schema(schemas, base_schema, least_common_schema, false);
1742
1.41k
    if (!st.ok()) {
1743
0
        return base_schema;
1744
0
    }
1745
1.41k
    return least_common_schema;
1746
1.41k
}
1747
1748
bool inherit_index(const std::vector<const TabletIndex*>& parent_indexes,
1749
                   TabletIndexes& subcolumns_indexes, FieldType column_type,
1750
131k
                   const std::string& suffix_path, bool is_array_nested_type) {
1751
131k
    if (parent_indexes.empty()) {
1752
123k
        return false;
1753
123k
    }
1754
8.18k
    subcolumns_indexes.clear();
1755
    // bkd index or array index only need to inherit one index
1756
8.18k
    if (field_is_numeric_type(column_type) ||
1757
8.18k
        (is_array_nested_type &&
1758
5.37k
         (field_is_numeric_type(column_type) || field_is_slice_type(column_type)))) {
1759
2.82k
        auto index_ptr = std::make_shared<TabletIndex>(*parent_indexes[0]);
1760
2.82k
        index_ptr->set_escaped_escaped_index_suffix_path(suffix_path);
1761
        // no need parse for bkd index or array index
1762
2.82k
        index_ptr->remove_parser_and_analyzer();
1763
2.82k
        subcolumns_indexes.emplace_back(std::move(index_ptr));
1764
2.82k
        return true;
1765
2.82k
    }
1766
    // string type need to inherit all indexes
1767
5.36k
    else if (field_is_slice_type(column_type) && !is_array_nested_type) {
1768
5.34k
        for (const auto& index : parent_indexes) {
1769
5.34k
            auto index_ptr = std::make_shared<TabletIndex>(*index);
1770
5.34k
            index_ptr->set_escaped_escaped_index_suffix_path(suffix_path);
1771
5.34k
            subcolumns_indexes.emplace_back(std::move(index_ptr));
1772
5.34k
        }
1773
5.32k
        return true;
1774
5.32k
    }
1775
48
    return false;
1776
8.18k
}
1777
1778
bool inherit_index(const std::vector<const TabletIndex*>& parent_indexes,
1779
131k
                   TabletIndexes& subcolumns_indexes, const TabletColumn& column) {
1780
131k
    if (!column.is_extracted_column()) {
1781
3
        return false;
1782
3
    }
1783
131k
    if (column.is_array_type()) {
1784
1.11k
        if (column.get_sub_columns().empty()) {
1785
0
            return false;
1786
0
        }
1787
1.11k
        const TabletColumn* nested = column.get_sub_columns()[0].get();
1788
1.11k
        while (nested != nullptr && nested->is_array_type()) {
1789
0
            if (nested->get_sub_columns().empty()) {
1790
0
                return false;
1791
0
            }
1792
0
            nested = nested->get_sub_columns()[0].get();
1793
0
        }
1794
1.11k
        if (nested == nullptr) {
1795
0
            return false;
1796
0
        }
1797
1.11k
        return inherit_index(parent_indexes, subcolumns_indexes, nested->type(),
1798
1.11k
                             column.path_info_ptr()->get_path(), true);
1799
1.11k
    }
1800
130k
    return inherit_index(parent_indexes, subcolumns_indexes, column.type(),
1801
130k
                         column.path_info_ptr()->get_path());
1802
131k
}
1803
1804
bool inherit_index(const std::vector<const TabletIndex*>& parent_indexes,
1805
0
                   TabletIndexes& subcolumns_indexes, const ColumnMetaPB& column_pb) {
1806
0
    if (!column_pb.has_column_path_info()) {
1807
0
        return false;
1808
0
    }
1809
0
    if (column_pb.type() == (int)FieldType::OLAP_FIELD_TYPE_ARRAY) {
1810
0
        if (column_pb.children_columns_size() == 0) {
1811
0
            return false;
1812
0
        }
1813
0
        const ColumnMetaPB* nested = &column_pb.children_columns(0);
1814
0
        while (nested != nullptr && nested->type() == (int)FieldType::OLAP_FIELD_TYPE_ARRAY) {
1815
0
            if (nested->children_columns_size() == 0) {
1816
0
                return false;
1817
0
            }
1818
0
            nested = &nested->children_columns(0);
1819
0
        }
1820
0
        if (nested == nullptr) {
1821
0
            return false;
1822
0
        }
1823
0
        return inherit_index(parent_indexes, subcolumns_indexes, (FieldType)nested->type(),
1824
0
                             column_pb.column_path_info().path(), true);
1825
0
    }
1826
0
    return inherit_index(parent_indexes, subcolumns_indexes, (FieldType)column_pb.type(),
1827
0
                         column_pb.column_path_info().path());
1828
0
}
1829
1830
// ============ Implementation from parse2column.cpp ============
1831
1832
/** Pool for objects that cannot be used from different threads simultaneously.
1833
  * Allows to create an object for each thread.
1834
  * Pool has unbounded size and objects are not destroyed before destruction of pool.
1835
  *
1836
  * Use it in cases when thread local storage is not appropriate
1837
  *  (when maximum number of simultaneously used objects is less
1838
  *   than number of running/sleeping threads, that has ever used object,
1839
  *   and creation/destruction of objects is expensive).
1840
  */
1841
template <typename T>
1842
class SimpleObjectPool {
1843
protected:
1844
    /// Hold all available objects in stack.
1845
    std::mutex mutex;
1846
    std::stack<std::unique_ptr<T>> stack;
1847
    /// Specialized deleter for std::unique_ptr.
1848
    /// Returns underlying pointer back to stack thus reclaiming its ownership.
1849
    struct Deleter {
1850
        SimpleObjectPool<T>* parent;
1851
20.3k
        Deleter(SimpleObjectPool<T>* parent_ = nullptr) : parent {parent_} {} /// NOLINT
1852
20.3k
        void operator()(T* owning_ptr) const {
1853
20.3k
            std::lock_guard lock {parent->mutex};
1854
20.3k
            parent->stack.emplace(owning_ptr);
1855
20.3k
        }
1856
    };
1857
1858
public:
1859
    using Pointer = std::unique_ptr<T, Deleter>;
1860
    /// Extracts and returns a pointer from the stack if it's not empty,
1861
    ///  creates a new one by calling provided f() otherwise.
1862
    template <typename Factory>
1863
20.3k
    Pointer get(Factory&& f) {
1864
20.3k
        std::unique_lock lock(mutex);
1865
20.3k
        if (stack.empty()) {
1866
27
            return {f(), this};
1867
27
        }
1868
20.3k
        auto object = stack.top().release();
1869
20.3k
        stack.pop();
1870
20.3k
        return std::unique_ptr<T, Deleter>(object, Deleter(this));
1871
20.3k
    }
variant_util.cpp:_ZN5doris12variant_util16SimpleObjectPoolINS_14JSONDataParserINS_14SimdJSONParserEEEE3getIZNS0_21parse_json_to_variantERNS_7IColumnERKNS_9StringRefEPS4_RKNS_11ParseConfigEE3$_0EESt10unique_ptrIS4_NS5_7DeleterEEOT_
Line
Count
Source
1863
15.7k
    Pointer get(Factory&& f) {
1864
15.7k
        std::unique_lock lock(mutex);
1865
15.7k
        if (stack.empty()) {
1866
1
            return {f(), this};
1867
1
        }
1868
15.7k
        auto object = stack.top().release();
1869
15.7k
        stack.pop();
1870
15.7k
        return std::unique_ptr<T, Deleter>(object, Deleter(this));
1871
15.7k
    }
variant_util.cpp:_ZN5doris12variant_util16SimpleObjectPoolINS_14JSONDataParserINS_14SimdJSONParserEEEE3getIZNS0_21parse_json_to_variantERNS_7IColumnERKNS_9ColumnStrIjEERKNS_11ParseConfigEE3$_0EESt10unique_ptrIS4_NS5_7DeleterEEOT_
Line
Count
Source
1863
4.56k
    Pointer get(Factory&& f) {
1864
4.56k
        std::unique_lock lock(mutex);
1865
4.56k
        if (stack.empty()) {
1866
26
            return {f(), this};
1867
26
        }
1868
4.54k
        auto object = stack.top().release();
1869
4.54k
        stack.pop();
1870
4.54k
        return std::unique_ptr<T, Deleter>(object, Deleter(this));
1871
4.56k
    }
1872
    /// Like get(), but creates object using default constructor.
1873
    Pointer getDefault() {
1874
        return get([] { return new T; });
1875
    }
1876
};
1877
1878
SimpleObjectPool<JsonParser> parsers_pool;
1879
1880
using Node = typename ColumnVariant::Subcolumns::Node;
1881
1882
8.59M
static inline void append_binary_bytes(ColumnString::Chars& chars, const void* data, size_t size) {
1883
8.59M
    const auto old_size = chars.size();
1884
8.59M
    chars.resize(old_size + size);
1885
8.59M
    memcpy(chars.data() + old_size, reinterpret_cast<const char*>(data), size);
1886
8.59M
}
1887
1888
3.28M
static inline void append_binary_type(ColumnString::Chars& chars, FieldType type) {
1889
3.28M
    const uint8_t t = static_cast<uint8_t>(type);
1890
3.28M
    append_binary_bytes(chars, &t, sizeof(uint8_t));
1891
3.28M
}
1892
1893
2.31M
static inline void append_binary_sizet(ColumnString::Chars& chars, size_t v) {
1894
2.31M
    append_binary_bytes(chars, &v, sizeof(size_t));
1895
2.31M
}
1896
1897
3.28M
void append_field_to_binary_chars(const Field& field, ColumnString::Chars& chars) {
1898
3.28M
    switch (field.get_type()) {
1899
1
    case PrimitiveType::TYPE_NULL: {
1900
1
        append_binary_type(chars, FieldType::OLAP_FIELD_TYPE_NONE);
1901
1
        return;
1902
0
    }
1903
182k
    case PrimitiveType::TYPE_BOOLEAN: {
1904
182k
        append_binary_type(chars,
1905
182k
                           TabletColumn::get_field_type_by_type(PrimitiveType::TYPE_BOOLEAN));
1906
182k
        const auto v = static_cast<UInt8>(field.get<PrimitiveType::TYPE_BOOLEAN>());
1907
182k
        append_binary_bytes(chars, &v, sizeof(UInt8));
1908
182k
        return;
1909
0
    }
1910
758k
    case PrimitiveType::TYPE_BIGINT: {
1911
758k
        append_binary_type(chars, TabletColumn::get_field_type_by_type(PrimitiveType::TYPE_BIGINT));
1912
758k
        const auto v = field.get<PrimitiveType::TYPE_BIGINT>();
1913
758k
        append_binary_bytes(chars, &v, sizeof(Int64));
1914
758k
        return;
1915
0
    }
1916
1
    case PrimitiveType::TYPE_LARGEINT: {
1917
1
        append_binary_type(chars,
1918
1
                           TabletColumn::get_field_type_by_type(PrimitiveType::TYPE_LARGEINT));
1919
1
        const auto v = field.get<PrimitiveType::TYPE_LARGEINT>();
1920
1
        append_binary_bytes(chars, &v, sizeof(int128_t));
1921
1
        return;
1922
0
    }
1923
61.2k
    case PrimitiveType::TYPE_DOUBLE: {
1924
61.2k
        append_binary_type(chars, TabletColumn::get_field_type_by_type(PrimitiveType::TYPE_DOUBLE));
1925
61.2k
        const auto v = field.get<PrimitiveType::TYPE_DOUBLE>();
1926
61.2k
        append_binary_bytes(chars, &v, sizeof(Float64));
1927
61.2k
        return;
1928
0
    }
1929
2.11M
    case PrimitiveType::TYPE_STRING: {
1930
2.11M
        append_binary_type(chars, FieldType::OLAP_FIELD_TYPE_STRING);
1931
2.11M
        const auto& v = field.get<PrimitiveType::TYPE_STRING>();
1932
2.11M
        append_binary_sizet(chars, v.size());
1933
2.11M
        append_binary_bytes(chars, v.data(), v.size());
1934
2.11M
        return;
1935
0
    }
1936
34.1k
    case PrimitiveType::TYPE_JSONB: {
1937
34.1k
        append_binary_type(chars, FieldType::OLAP_FIELD_TYPE_JSONB);
1938
34.1k
        const auto& v = field.get<PrimitiveType::TYPE_JSONB>();
1939
34.1k
        append_binary_sizet(chars, v.get_size());
1940
34.1k
        append_binary_bytes(chars, v.get_value(), v.get_size());
1941
34.1k
        return;
1942
0
    }
1943
168k
    case PrimitiveType::TYPE_ARRAY: {
1944
168k
        append_binary_type(chars, FieldType::OLAP_FIELD_TYPE_ARRAY);
1945
168k
        const auto& a = field.get<PrimitiveType::TYPE_ARRAY>();
1946
168k
        append_binary_sizet(chars, a.size());
1947
179k
        for (const auto& elem : a) {
1948
179k
            append_field_to_binary_chars(elem, chars);
1949
179k
        }
1950
168k
        return;
1951
0
    }
1952
0
    default:
1953
0
        throw doris::Exception(ErrorCode::INVALID_ARGUMENT, "Unsupported field type {}",
1954
0
                               field.get_type());
1955
3.28M
    }
1956
3.28M
}
1957
/// Visitor that keeps @num_dimensions_to_keep dimensions in arrays
1958
/// and replaces all scalars or nested arrays to @replacement at that level.
1959
class FieldVisitorReplaceScalars : public StaticVisitor<Field> {
1960
public:
1961
    FieldVisitorReplaceScalars(const Field& replacement_, size_t num_dimensions_to_keep_)
1962
0
            : replacement(replacement_), num_dimensions_to_keep(num_dimensions_to_keep_) {}
1963
    template <PrimitiveType T>
1964
    Field operator()(const typename PrimitiveTypeTraits<T>::CppType& x) const {
1965
        if constexpr (T == TYPE_ARRAY) {
1966
            if (num_dimensions_to_keep == 0) {
1967
                return replacement;
1968
            }
1969
            const size_t size = x.size();
1970
            Array res(size);
1971
            for (size_t i = 0; i < size; ++i) {
1972
                res[i] = apply_visitor(
1973
                        FieldVisitorReplaceScalars(replacement, num_dimensions_to_keep - 1), x[i]);
1974
            }
1975
            return Field::create_field<TYPE_ARRAY>(res);
1976
        } else {
1977
            return replacement;
1978
        }
1979
    }
1980
1981
private:
1982
    const Field& replacement;
1983
    size_t num_dimensions_to_keep;
1984
};
1985
1986
/// Parse JSON to ParseResult only (no insertion into ColumnVariant).
1987
/// Handles empty strings and parse failures with fallback to string root.
1988
template <typename ParserImpl>
1989
static ParseResult parse_json_to_result(const char* src, size_t length,
1990
                                        JSONDataParser<ParserImpl>* parser,
1991
1.35M
                                        const ParseConfig& config) {
1992
1.35M
    std::optional<ParseResult> result;
1993
    /// Treat empty string as an empty object
1994
    /// for better CAST from String to Object.
1995
1.35M
    if (length > 0) {
1996
1.35M
        result = parser->parse(src, length, config);
1997
1.35M
    } else {
1998
308
        result = ParseResult {};
1999
308
    }
2000
1.35M
    if (!result) {
2001
664
        VLOG_DEBUG << "failed to parse " << std::string_view(src, length) << ", length= " << length;
2002
664
        if (config::variant_throw_exeception_on_invalid_json) {
2003
0
            throw doris::Exception(ErrorCode::INVALID_ARGUMENT, "Failed to parse object {}",
2004
0
                                   std::string_view(src, length));
2005
0
        }
2006
        // Treat as string
2007
664
        PathInData root_path;
2008
664
        Field field = Field::create_field<TYPE_STRING>(String(src, length));
2009
664
        result = ParseResult {{root_path}, {field}};
2010
664
    }
2011
1.35M
    return std::move(*result);
2012
1.35M
}
2013
2014
/// Insert a pre-parsed ParseResult into ColumnVariant using the specified parse mode.
2015
static void insert_parse_result_into_variant(IColumn& column, ParseResult&& result,
2016
1.35M
                                             const ParseConfig& config) {
2017
1.35M
    auto& column_variant = assert_cast<ColumnVariant&>(column);
2018
1.35M
    auto& [paths, values] = result;
2019
1.35M
    assert(paths.size() == values.size());
2020
1.35M
    size_t old_num_rows = column_variant.rows();
2021
1.35M
    if (config.deprecated_enable_flatten_nested) {
2022
        // here we should check the paths in variant and paths in result,
2023
        // if two paths which same prefix have different structure, we should throw an exception
2024
3.02k
        std::vector<PathInData> check_paths;
2025
12.0k
        for (const auto& entry : column_variant.get_subcolumns()) {
2026
12.0k
            check_paths.push_back(entry->path);
2027
12.0k
        }
2028
3.02k
        check_paths.insert(check_paths.end(), paths.begin(), paths.end());
2029
3.02k
        THROW_IF_ERROR(check_variant_has_no_ambiguous_paths(check_paths));
2030
3.02k
    }
2031
1.35M
    auto [doc_value_data_paths, doc_value_data_values] =
2032
1.35M
            column_variant.get_doc_value_data_paths_and_values();
2033
1.35M
    auto& doc_value_data_offsets = column_variant.serialized_doc_value_column_offsets();
2034
2035
14.4M
    auto flush_defaults = [](ColumnVariant::Subcolumn* subcolumn) {
2036
14.4M
        const auto num_defaults = subcolumn->cur_num_of_defaults();
2037
14.4M
        if (num_defaults > 0) {
2038
1.43M
            subcolumn->insert_many_defaults(num_defaults);
2039
1.43M
            subcolumn->reset_current_num_of_defaults();
2040
1.43M
        }
2041
14.4M
    };
2042
2043
1.35M
    auto is_plain_path = [](const PathInData& path) {
2044
24.9k
        for (const auto& part : path.get_parts()) {
2045
24.9k
            if (part.is_nested || part.anonymous_array_level != 0) {
2046
0
                return false;
2047
0
            }
2048
24.9k
        }
2049
24.9k
        return true;
2050
24.9k
    };
2051
2052
1.35M
    auto get_or_create_subcolumn = [&](const PathInData& path, size_t index_hint,
2053
14.4M
                                       const FieldInfo& field_info) -> ColumnVariant::Subcolumn* {
2054
14.4M
        auto* subcolumn = column_variant.get_subcolumn(path, index_hint);
2055
14.4M
        if (subcolumn == nullptr) {
2056
47.6k
            if (path.has_nested_part()) {
2057
9
                column_variant.add_nested_subcolumn(path, field_info, old_num_rows);
2058
47.6k
            } else {
2059
47.6k
                column_variant.add_sub_column(path, old_num_rows);
2060
47.6k
            }
2061
47.6k
            subcolumn = column_variant.get_subcolumn(path, index_hint);
2062
47.6k
        }
2063
14.4M
        if (!subcolumn) {
2064
0
            throw doris::Exception(ErrorCode::INVALID_ARGUMENT, "Failed to find sub column {}",
2065
0
                                   path.get_path());
2066
0
        }
2067
14.4M
        return subcolumn;
2068
14.4M
    };
2069
2070
14.2M
    auto normalize_plain_path = [&](const PathInData& path) {
2071
14.2M
        if (!config.check_duplicate_json_path || path.empty() || !is_plain_path(path)) {
2072
14.2M
            return path;
2073
14.2M
        }
2074
6.72k
        return PathInData(path.get_path());
2075
14.2M
    };
2076
2077
1.35M
    auto insert_into_subcolumn = [&](size_t i,
2078
14.4M
                                     bool check_size_mismatch) -> ColumnVariant::Subcolumn* {
2079
14.4M
        FieldInfo field_info;
2080
14.4M
        get_field_info(values[i], &field_info);
2081
14.4M
        if (field_info.scalar_type_id == PrimitiveType::INVALID_TYPE) {
2082
26.8k
            return nullptr;
2083
26.8k
        }
2084
14.4M
        auto path = normalize_plain_path(paths[i]);
2085
14.4M
        auto* subcolumn = get_or_create_subcolumn(path, i, field_info);
2086
14.4M
        flush_defaults(subcolumn);
2087
14.4M
        if (check_size_mismatch && subcolumn->size() != old_num_rows) {
2088
1
            throw doris::Exception(ErrorCode::INVALID_ARGUMENT,
2089
1
                                   "subcolumn {} size missmatched, may contains duplicated entry",
2090
1
                                   path.get_path());
2091
1
        }
2092
14.4M
        subcolumn->insert(std::move(values[i]), std::move(field_info));
2093
14.4M
        return subcolumn;
2094
14.4M
    };
2095
2096
1.35M
    switch (config.parse_to) {
2097
1.17M
    case ParseConfig::ParseTo::OnlySubcolumns:
2098
17.0M
        for (size_t i = 0; i < paths.size(); ++i) {
2099
15.8M
            insert_into_subcolumn(i, true);
2100
15.8M
        }
2101
1.17M
        break;
2102
177k
    case ParseConfig::ParseTo::OnlyDocValueColumn: {
2103
18.4E
        CHECK(column_variant.enable_doc_mode()) << "OnlyDocValueColumn requires doc mode enabled";
2104
177k
        std::vector<size_t> doc_item_indexes;
2105
177k
        doc_item_indexes.reserve(paths.size());
2106
177k
        phmap::flat_hash_set<StringRef, StringRefHash> seen_paths;
2107
177k
        seen_paths.reserve(paths.size());
2108
2109
3.41M
        for (size_t i = 0; i < paths.size(); ++i) {
2110
3.23M
            FieldInfo field_info;
2111
3.23M
            get_field_info(values[i], &field_info);
2112
3.23M
            if (paths[i].empty()) {
2113
710
                auto* subcolumn = column_variant.get_subcolumn(paths[i]);
2114
710
                DCHECK(subcolumn != nullptr);
2115
710
                flush_defaults(subcolumn);
2116
710
                subcolumn->insert(std::move(values[i]), std::move(field_info));
2117
710
                continue;
2118
710
            }
2119
3.23M
            if (field_info.scalar_type_id == PrimitiveType::INVALID_TYPE ||
2120
3.23M
                values[i].get_type() == PrimitiveType::TYPE_NULL) {
2121
89.8k
                continue;
2122
89.8k
            }
2123
3.14M
            const auto& path_str = paths[i].get_path();
2124
3.14M
            StringRef path_ref {path_str.data(), path_str.size()};
2125
3.14M
            if (UNLIKELY(!seen_paths.emplace(path_ref).second)) {
2126
0
                throw doris::Exception(ErrorCode::INVALID_ARGUMENT,
2127
0
                                       "may contains duplicated entry : {}",
2128
0
                                       std::string_view(path_str));
2129
0
            }
2130
3.14M
            doc_item_indexes.push_back(i);
2131
3.14M
        }
2132
2133
177k
        std::sort(doc_item_indexes.begin(), doc_item_indexes.end(),
2134
20.9M
                  [&](size_t l, size_t r) { return paths[l].get_path() < paths[r].get_path(); });
2135
3.10M
        for (const auto idx : doc_item_indexes) {
2136
3.10M
            const auto& path_str = paths[idx].get_path();
2137
3.10M
            doc_value_data_paths->insert_data(path_str.data(), path_str.size());
2138
3.10M
            auto& chars = doc_value_data_values->get_chars();
2139
3.10M
            append_field_to_binary_chars(values[idx], chars);
2140
3.10M
            doc_value_data_values->get_offsets().push_back(chars.size());
2141
3.10M
        }
2142
177k
    } break;
2143
1.35M
    }
2144
1.35M
    doc_value_data_offsets.push_back(doc_value_data_paths->size());
2145
    // /// Insert default values to missed subcolumns.
2146
1.35M
    const auto& subcolumns = column_variant.get_subcolumns();
2147
30.3M
    for (const auto& entry : subcolumns) {
2148
30.3M
        if (entry->data.size() == old_num_rows) {
2149
            // Handle nested paths differently from simple paths
2150
14.4M
            if (entry->path.has_nested_part()) {
2151
                // Try to insert default from nested, if failed, insert regular default
2152
0
                bool success = UNLIKELY(column_variant.try_insert_default_from_nested(entry));
2153
0
                if (!success) {
2154
0
                    entry->data.insert_default();
2155
0
                }
2156
14.4M
            } else {
2157
                // For non-nested paths, increment default counter
2158
14.4M
                entry->data.increment_default_counter();
2159
14.4M
            }
2160
14.4M
        }
2161
30.3M
    }
2162
1.35M
    column_variant.incr_num_rows();
2163
1.35M
    auto sparse_column = column_variant.get_sparse_column();
2164
1.35M
    if (sparse_column->size() == old_num_rows) {
2165
1.35M
        sparse_column->assume_mutable()->insert_default();
2166
1.35M
    }
2167
1.35M
#ifndef NDEBUG
2168
1.35M
    column_variant.check_consistency();
2169
1.35M
#endif
2170
1.35M
}
2171
2172
/// Original combined parse+insert function, now delegates to the two-step functions.
2173
template <typename ParserImpl>
2174
void parse_json_to_variant_impl(IColumn& column, const char* src, size_t length,
2175
1.35M
                                JSONDataParser<ParserImpl>* parser, const ParseConfig& config) {
2176
1.35M
    auto result = parse_json_to_result(src, length, parser, config);
2177
1.35M
    insert_parse_result_into_variant(column, std::move(result), config);
2178
1.35M
}
2179
2180
// exposed interfaces
2181
void parse_json_to_variant(IColumn& column, const StringRef& json, JsonParser* parser,
2182
15.7k
                           const ParseConfig& config) {
2183
15.7k
    if (parser) {
2184
0
        return parse_json_to_variant_impl(column, json.data, json.size, parser, config);
2185
15.7k
    } else {
2186
15.7k
        auto pool_parser = parsers_pool.get([] { return new JsonParser(); });
2187
15.7k
        return parse_json_to_variant_impl(column, json.data, json.size, pool_parser.get(), config);
2188
15.7k
    }
2189
15.7k
}
2190
2191
void parse_json_to_variant(IColumn& column, const ColumnString& raw_json_column,
2192
4.56k
                           const ParseConfig& config) {
2193
4.56k
    auto parser = parsers_pool.get([] { return new JsonParser(); });
2194
1.34M
    for (size_t i = 0; i < raw_json_column.size(); ++i) {
2195
1.34M
        StringRef raw_json = raw_json_column.get_data_at(i);
2196
1.34M
        parse_json_to_variant_impl(column, raw_json.data, raw_json.size, parser.get(), config);
2197
1.34M
    }
2198
4.56k
    column.finalize();
2199
4.56k
}
2200
2201
// parse the doc snapshot column to subcolumns
2202
0
void materialize_docs_to_subcolumns(ColumnVariant& column_variant) {
2203
0
    auto subcolumns = materialize_docs_to_subcolumns_map(column_variant);
2204
2205
0
    for (auto& entry : subcolumns) {
2206
0
        entry.second.finalize();
2207
0
        if (!column_variant.add_sub_column(PathInData(entry.first),
2208
0
                                           IColumn::mutate(entry.second.get_finalized_column_ptr()),
2209
0
                                           entry.second.get_least_common_type())) {
2210
0
            throw doris::Exception(ErrorCode::INTERNAL_ERROR,
2211
0
                                   "Failed to add subcolumn {}, which is from doc snapshot column",
2212
0
                                   entry.first);
2213
0
        }
2214
0
    }
2215
2216
0
    column_variant.finalize();
2217
0
}
2218
2219
// ============ Implementation from variant_util.cpp ============
2220
2221
phmap::flat_hash_map<std::string_view, ColumnVariant::Subcolumn> materialize_docs_to_subcolumns_map(
2222
11
        const ColumnVariant& variant, size_t expected_unique_paths) {
2223
11
    constexpr size_t kInitialPathReserve = 8192;
2224
11
    phmap::flat_hash_map<std::string_view, ColumnVariant::Subcolumn> subcolumns;
2225
2226
11
    const auto [column_key, column_value] = variant.get_doc_value_data_paths_and_values();
2227
11
    const auto& column_offsets = variant.serialized_doc_value_column_offsets();
2228
11
    const size_t num_rows = column_offsets.size();
2229
2230
11
    DCHECK_EQ(num_rows, variant.size()) << "doc snapshot offsets size mismatch with variant rows";
2231
2232
11
    subcolumns.reserve(expected_unique_paths != 0
2233
11
                               ? expected_unique_paths
2234
11
                               : std::min<size_t>(column_key->size(), kInitialPathReserve));
2235
2236
506
    for (size_t row = 0; row < num_rows; ++row) {
2237
495
        const size_t start = column_offsets[row - 1];
2238
495
        const size_t end = column_offsets[row];
2239
6.33k
        for (size_t i = start; i < end; ++i) {
2240
5.83k
            const auto& key = column_key->get_data_at(i);
2241
5.83k
            const std::string_view path_sv(key.data, key.size);
2242
2243
5.83k
            auto [it, inserted] =
2244
5.83k
                    subcolumns.try_emplace(path_sv, ColumnVariant::Subcolumn {0, true, false});
2245
5.83k
            auto& subcolumn = it->second;
2246
5.83k
            if (inserted) {
2247
62
                subcolumn.insert_many_defaults(row);
2248
5.77k
            } else if (subcolumn.size() != row) {
2249
4
                subcolumn.insert_many_defaults(row - subcolumn.size());
2250
4
            }
2251
5.83k
            subcolumn.deserialize_from_binary_column(column_value, i);
2252
5.83k
        }
2253
495
    }
2254
2255
62
    for (auto& [path, subcolumn] : subcolumns) {
2256
62
        if (subcolumn.size() != num_rows) {
2257
7
            subcolumn.insert_many_defaults(num_rows - subcolumn.size());
2258
7
        }
2259
62
    }
2260
2261
11
    return subcolumns;
2262
11
}
2263
2264
Status _parse_and_materialize_variant_columns(Block& block,
2265
                                              const std::vector<uint32_t>& variant_pos,
2266
4.58k
                                              const std::vector<ParseConfig>& configs) {
2267
10.1k
    for (size_t i = 0; i < variant_pos.size(); ++i) {
2268
5.51k
        auto column_ref = block.get_by_position(variant_pos[i]).column;
2269
5.51k
        bool is_nullable = column_ref->is_nullable();
2270
5.51k
        MutableColumnPtr var_column = column_ref->assume_mutable();
2271
5.51k
        if (is_nullable) {
2272
5.07k
            const auto& nullable = assert_cast<const ColumnNullable&>(*column_ref);
2273
5.07k
            var_column = nullable.get_nested_column_ptr()->assume_mutable();
2274
5.07k
        }
2275
5.51k
        auto& var = assert_cast<ColumnVariant&>(*var_column);
2276
5.51k
        var_column->finalize();
2277
2278
5.51k
        MutableColumnPtr variant_column;
2279
5.51k
        if (!var.is_scalar_variant()) {
2280
            // Already parsed (non-scalar variant from query reader).
2281
1.17k
            continue;
2282
1.17k
        }
2283
2284
4.34k
        VLOG_DEBUG << "parse scalar variant column: " << var.get_root_type()->get_name();
2285
4.34k
        ColumnPtr scalar_root_column;
2286
4.34k
        if (var.get_root_type()->get_primitive_type() == TYPE_JSONB) {
2287
            // TODO more efficient way to parse jsonb type, currently we just convert jsonb to
2288
            // json str and parse them into variant
2289
31
            RETURN_IF_ERROR(cast_column({var.get_root(), var.get_root_type(), ""},
2290
31
                                        var.get_root()->is_nullable()
2291
31
                                                ? make_nullable(std::make_shared<DataTypeString>())
2292
31
                                                : std::make_shared<DataTypeString>(),
2293
31
                                        &scalar_root_column));
2294
31
            if (scalar_root_column->is_nullable()) {
2295
31
                scalar_root_column = assert_cast<const ColumnNullable*>(scalar_root_column.get())
2296
31
                                             ->get_nested_column_ptr();
2297
31
            }
2298
4.31k
        } else {
2299
4.31k
            const auto& root = *var.get_root();
2300
4.31k
            scalar_root_column =
2301
4.31k
                    root.is_nullable()
2302
4.31k
                            ? assert_cast<const ColumnNullable&>(root).get_nested_column_ptr()
2303
4.31k
                            : var.get_root();
2304
4.31k
        }
2305
2306
4.34k
        if (scalar_root_column->is_column_string()) {
2307
4.34k
            variant_column = ColumnVariant::create(0, var.enable_doc_mode());
2308
4.34k
            parse_json_to_variant(*variant_column.get(),
2309
4.34k
                                  assert_cast<const ColumnString&>(*scalar_root_column),
2310
4.34k
                                  configs[i]);
2311
4.34k
        } else {
2312
            // Root maybe other types rather than string like ColumnVariant(Int32).
2313
            // In this case, we should finlize the root and cast to JSON type
2314
1
            auto expected_root_type =
2315
1
                    make_nullable(std::make_shared<ColumnVariant::MostCommonType>());
2316
1
            var.ensure_root_node_type(expected_root_type);
2317
1
            variant_column = var.assume_mutable();
2318
1
        }
2319
2320
        // Wrap variant with nullmap if it is nullable
2321
4.34k
        ColumnPtr result = variant_column->get_ptr();
2322
4.34k
        if (is_nullable) {
2323
4.15k
            const auto& null_map =
2324
4.15k
                    assert_cast<const ColumnNullable&>(*column_ref).get_null_map_column_ptr();
2325
4.15k
            result = ColumnNullable::create(result, null_map);
2326
4.15k
        }
2327
4.34k
        block.get_by_position(variant_pos[i]).column = result;
2328
4.34k
    }
2329
4.58k
    return Status::OK();
2330
4.58k
}
2331
2332
Status parse_and_materialize_variant_columns(Block& block, const std::vector<uint32_t>& variant_pos,
2333
4.59k
                                             const std::vector<ParseConfig>& configs) {
2334
4.59k
    RETURN_IF_CATCH_EXCEPTION(
2335
4.59k
            { return _parse_and_materialize_variant_columns(block, variant_pos, configs); });
2336
4.59k
}
2337
2338
Status parse_and_materialize_variant_columns(Block& block, const TabletSchema& tablet_schema,
2339
4.69k
                                             const std::vector<uint32_t>& column_pos) {
2340
4.69k
    std::vector<uint32_t> variant_column_pos;
2341
4.69k
    std::vector<uint32_t> variant_schema_pos;
2342
4.69k
    variant_column_pos.reserve(column_pos.size());
2343
4.69k
    variant_schema_pos.reserve(column_pos.size());
2344
28.4k
    for (size_t block_pos = 0; block_pos < column_pos.size(); ++block_pos) {
2345
23.7k
        const uint32_t schema_pos = column_pos[block_pos];
2346
23.7k
        const auto& column = tablet_schema.column(schema_pos);
2347
23.7k
        if (column.is_variant_type()) {
2348
5.47k
            variant_column_pos.push_back(schema_pos);
2349
5.47k
            variant_schema_pos.push_back(schema_pos);
2350
5.47k
        }
2351
23.7k
    }
2352
2353
4.69k
    if (variant_column_pos.empty()) {
2354
47
        return Status::OK();
2355
47
    }
2356
2357
4.65k
    std::vector<ParseConfig> configs(variant_column_pos.size());
2358
10.0k
    for (size_t i = 0; i < variant_column_pos.size(); ++i) {
2359
        // Deprecated legacy flatten-nested switch. Distinct from variant_enable_nested_group.
2360
5.44k
        configs[i].deprecated_enable_flatten_nested =
2361
5.44k
                tablet_schema.deprecated_variant_flatten_nested();
2362
5.44k
        configs[i].check_duplicate_json_path = config::variant_enable_duplicate_json_path_check;
2363
5.44k
        const auto& column = tablet_schema.column(variant_schema_pos[i]);
2364
5.44k
        if (!column.is_variant_type()) {
2365
0
            return Status::InternalError("column is not variant type, column name: {}",
2366
0
                                         column.name());
2367
0
        }
2368
        // if doc mode is not enabled, no need to parse to doc value column
2369
5.44k
        if (!column.variant_enable_doc_mode()) {
2370
3.32k
            configs[i].parse_to = ParseConfig::ParseTo::OnlySubcolumns;
2371
3.32k
            continue;
2372
3.32k
        }
2373
2374
2.12k
        configs[i].parse_to = ParseConfig::ParseTo::OnlyDocValueColumn;
2375
2.12k
    }
2376
2377
4.65k
    RETURN_IF_ERROR(parse_and_materialize_variant_columns(block, variant_column_pos, configs));
2378
4.64k
    return Status::OK();
2379
4.65k
}
2380
2381
} // namespace doris::variant_util