Coverage Report

Created: 2026-09-16 19:59

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/storage/tablet_info.h
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
#pragma once
19
20
#include <butil/fast_rand.h>
21
#include <gen_cpp/Descriptors_types.h>
22
#include <gen_cpp/Types_types.h>
23
#include <gen_cpp/descriptors.pb.h>
24
#include <gen_cpp/olap_file.pb.h>
25
26
#include <cstdint>
27
#include <functional>
28
#include <iterator>
29
#include <map>
30
#include <memory>
31
#include <string>
32
#include <tuple>
33
#include <unordered_map>
34
#include <utility>
35
#include <vector>
36
37
#include "cloud/config.h"
38
#include "common/cast_set.h"
39
#include "common/logging.h"
40
#include "common/object_pool.h"
41
#include "common/status.h"
42
#include "core/block/block.h"
43
#include "core/block/column_with_type_and_name.h"
44
#include "core/column/column.h"
45
#include "exprs/vexpr.h"
46
#include "exprs/vexpr_fwd.h"
47
#include "runtime/descriptors.h"
48
#include "util/raw_value.h"
49
50
namespace doris {
51
class MemTracker;
52
class SlotDescriptor;
53
class TExprNode;
54
class TabletColumn;
55
class TabletIndex;
56
class TupleDescriptor;
57
58
struct OlapTableIndexSchema {
59
    int64_t index_id;
60
    int64_t row_binlog_id = 0;
61
    PRowBinlogWriteColumnMappings row_binlog_column_mappings;
62
    std::vector<SlotDescriptor*> slots;
63
    int32_t schema_hash;
64
    std::vector<TabletColumn*> columns;
65
    std::vector<TabletIndex*> indexes;
66
    VExprContextSPtr where_clause;
67
68
    void to_protobuf(POlapTableIndexSchema* pindex) const;
69
};
70
71
class OlapTableSchemaParam {
72
public:
73
84
    OlapTableSchemaParam() = default;
74
84
    ~OlapTableSchemaParam() noexcept = default;
75
76
    Status init(const TOlapTableSchemaParam& tschema);
77
    Status init(const POlapTableSchemaParam& pschema);
78
79
178
    int64_t db_id() const { return _db_id; }
80
178
    int64_t table_id() const { return _table_id; }
81
80
    int64_t version() const { return _version; }
82
83
32
    TupleDescriptor* tuple_desc() const { return _tuple_desc; }
84
210
    const std::vector<OlapTableIndexSchema*>& indexes() const { return _indexes; }
85
    const OlapTableIndexSchema* row_binlog_index_schema(int64_t index_id) const;
86
0
    const std::vector<OlapTableIndexSchema*>& row_binlog_index_schemas() const {
87
0
        return _row_binlog_index_schemas;
88
0
    }
89
90
    void to_protobuf(POlapTableSchemaParam* pschema) const;
91
92
    // NOTE: this function is not thread-safe.
93
19
    POlapTableSchemaParam* to_protobuf() const {
94
19
        if (_proto_schema == nullptr) {
95
19
            _proto_schema = _obj_pool.add(new POlapTableSchemaParam());
96
19
            to_protobuf(_proto_schema);
97
19
        }
98
19
        return _proto_schema;
99
19
    }
100
101
51
    UniqueKeyUpdateModePB unique_key_update_mode() const { return _unique_key_update_mode; }
102
103
103
    bool is_partial_update() const {
104
103
        return _unique_key_update_mode != UniqueKeyUpdateModePB::UPSERT;
105
103
    }
106
2
    bool is_fixed_partial_update() const {
107
2
        return _unique_key_update_mode == UniqueKeyUpdateModePB::UPDATE_FIXED_COLUMNS;
108
2
    }
109
0
    bool is_flexible_partial_update() const {
110
0
        return _unique_key_update_mode == UniqueKeyUpdateModePB::UPDATE_FLEXIBLE_COLUMNS;
111
0
    }
112
113
51
    const std::set<std::string>& partial_update_input_columns() const {
114
51
        return _partial_update_input_columns;
115
51
    }
116
51
    PartialUpdateNewRowPolicyPB partial_update_new_key_policy() const {
117
51
        return _partial_update_new_row_policy;
118
51
    }
119
51
    std::string auto_increment_coulumn() const { return _auto_increment_column; }
120
2
    int32_t auto_increment_column_unique_id() const { return _auto_increment_column_unique_id; }
121
2
    void set_timestamp_ms(int64_t timestamp_ms) { _timestamp_ms = timestamp_ms; }
122
51
    int64_t timestamp_ms() const { return _timestamp_ms; }
123
2
    void set_nano_seconds(int32_t nano_seconds) { _nano_seconds = nano_seconds; }
124
51
    int32_t nano_seconds() const { return _nano_seconds; }
125
2
    void set_timezone(std::string timezone) { _timezone = timezone; }
126
51
    std::string timezone() const { return _timezone; }
127
51
    bool is_strict_mode() const { return _is_strict_mode; }
128
50
    int32_t sequence_map_col_uid() const { return _sequence_map_col_uid; }
129
    std::string debug_string() const;
130
131
    Status init_unique_key_update_mode(const TOlapTableSchemaParam& tschema);
132
133
private:
134
    int64_t _db_id;
135
    int64_t _table_id;
136
    int64_t _version;
137
138
    TupleDescriptor* _tuple_desc = nullptr;
139
    mutable POlapTableSchemaParam* _proto_schema = nullptr;
140
    std::vector<OlapTableIndexSchema*> _indexes;
141
    std::vector<OlapTableIndexSchema*> _row_binlog_index_schemas;
142
    mutable ObjectPool _obj_pool;
143
    UniqueKeyUpdateModePB _unique_key_update_mode {UniqueKeyUpdateModePB::UPSERT};
144
    PartialUpdateNewRowPolicyPB _partial_update_new_row_policy {
145
            PartialUpdateNewRowPolicyPB::APPEND};
146
    std::set<std::string> _partial_update_input_columns;
147
    bool _is_strict_mode = false;
148
    std::string _auto_increment_column;
149
    int32_t _auto_increment_column_unique_id;
150
    int64_t _timestamp_ms = 0;
151
    int32_t _nano_seconds {0};
152
    std::string _timezone;
153
    int32_t _sequence_map_col_uid {-1};
154
};
155
156
using OlapTableIndexTablets = TOlapTableIndexTablets;
157
// struct TOlapTableIndexTablets {
158
//     1: required i64 index_id
159
//     2: required list<i64> tablets
160
//     3: optional i64 bucket_be_id
161
//     4: optional list<i32> local_bucket_seqs
162
// }
163
164
using BlockRow = std::pair<Block*, int32_t>;
165
using BlockRowWithIndicator = std::tuple<Block*, int32_t, bool>; // [block, row, is_transformed]
166
167
struct VOlapTablePartition {
168
    int64_t id = 0;
169
    BlockRow start_key;
170
    BlockRow end_key;
171
    std::vector<BlockRow> in_keys;
172
    int64_t num_buckets = 0;
173
    std::vector<OlapTableIndexTablets> indexes;
174
    bool is_mutable;
175
    // -1 indicates partition with hash distribution
176
    int64_t load_tablet_idx = -1;
177
    // Fallback FE-selected bucket owner BE for adaptive random bucket mode. New FE versions send
178
    // this per index in OlapTableIndexTablets.
179
    int64_t bucket_be_id = -1;
180
    // Fallback bucket indices (0-based) used by FIND_TABLET_RANDOM_BUCKET rotation. New FE versions
181
    // send this per index in OlapTableIndexTablets.
182
    std::vector<int32_t> local_bucket_seqs;
183
    int total_replica_num = 0;
184
    int load_required_replica_num = 0;
185
    // tablet_id -> set of backend_ids that have version gaps
186
    std::unordered_map<int64_t, std::unordered_set<int64_t>> tablet_version_gap_backends;
187
188
    VOlapTablePartition(Block* partition_block)
189
            // the default value of partition bound is -1.
190
28
            : start_key {partition_block, -1}, end_key {partition_block, -1} {}
191
};
192
193
// this is only used by tablet_sink. so we can assume it's inited by its' descriptor.
194
class VOlapTablePartKeyComparator {
195
public:
196
    VOlapTablePartKeyComparator(const std::vector<uint16_t>& slot_locs,
197
                                const std::vector<uint16_t>& params_locs)
198
43
            : _slot_locs(slot_locs), _param_locs(params_locs) {}
199
200
    // return true if lhs < rhs
201
    // 'row' is -1 mean maximal boundary
202
    bool operator()(const BlockRowWithIndicator& lhs, const BlockRowWithIndicator& rhs) const;
203
204
private:
205
    const std::vector<uint16_t>& _slot_locs;
206
    const std::vector<uint16_t>& _param_locs;
207
};
208
209
// store an olap table's tablet information
210
class VOlapTablePartitionParam {
211
public:
212
    VOlapTablePartitionParam(std::shared_ptr<OlapTableSchemaParam>& schema,
213
                             const TOlapTablePartitionParam& param);
214
215
    ~VOlapTablePartitionParam();
216
217
    Status init();
218
219
4
    int64_t db_id() const { return _t_param.db_id; }
220
4
    int64_t table_id() const { return _t_param.table_id; }
221
0
    int64_t version() const { return _t_param.version; }
222
223
    // return true if we found this block_row in partition
224
    ALWAYS_INLINE bool find_partition(Block* block, int row,
225
31
                                      VOlapTablePartition*& partition) const {
226
31
        auto it = _is_in_partition ? _partitions_map->find(std::tuple {block, row, true})
227
31
                                   : _partitions_map->upper_bound(std::tuple {block, row, true});
228
31
        VLOG_TRACE << "find row " << row << " of\n"
229
0
                   << block->dump_data() << "in:\n"
230
0
                   << _partition_block.dump_data() << "result line row: " << std::get<1>(it->first);
231
232
        // for list partition it might result in default partition
233
31
        if (_is_in_partition) {
234
0
            partition = (it != _partitions_map->end()) ? it->second : _default_partition;
235
0
            it = _partitions_map->end();
236
0
        }
237
31
        if (it != _partitions_map->end() &&
238
31
            _part_contains(it->second, std::tuple {block, row, true})) {
239
27
            partition = it->second;
240
27
        }
241
31
        return (partition != nullptr);
242
31
    }
243
244
    ALWAYS_INLINE void find_tablets(
245
            Block* block, const std::vector<uint32_t>& indexes,
246
            const std::vector<VOlapTablePartition*>& partitions,
247
            std::vector<uint32_t>& tablet_indexes /*result*/,
248
            /*TODO: check if flat hash map will be better*/
249
14
            std::map<VOlapTablePartition*, int64_t>* partition_tablets_buffer = nullptr) const {
250
14
        std::function<uint32_t(Block*, uint32_t, const VOlapTablePartition&)> compute_function;
251
14
        if (!_distributed_slot_locs.empty()) {
252
            //TODO: refactor by saving the hash values. then we can calculate in columnwise.
253
11
            compute_function = [this](Block* block, uint32_t row,
254
14
                                      const VOlapTablePartition& partition) -> uint32_t {
255
14
                uint32_t hash_val = 0;
256
14
                for (unsigned short _distributed_slot_loc : _distributed_slot_locs) {
257
14
                    auto* slot_desc = _slots[_distributed_slot_loc];
258
14
                    auto& column = block->get_by_position(_distributed_slot_loc).column;
259
14
                    auto val = column->get_data_at(row);
260
14
                    if (val.data != nullptr) {
261
14
                        hash_val = RawValue::zlib_crc32(val.data, val.size,
262
14
                                                        slot_desc->type()->get_primitive_type(),
263
14
                                                        hash_val);
264
14
                    } else {
265
0
                        hash_val = HashUtil::zlib_crc_hash_null(hash_val);
266
0
                    }
267
14
                }
268
14
                return cast_set<uint32_t>(hash_val % partition.num_buckets);
269
14
            };
270
11
        } else { // random distribution
271
3
            compute_function = [](Block* block, uint32_t row,
272
3
                                  const VOlapTablePartition& partition) -> uint32_t {
273
3
                if (partition.load_tablet_idx == -1) {
274
                    // for compatible with old version, just do random
275
0
                    return cast_set<uint32_t>(butil::fast_rand() % partition.num_buckets);
276
0
                }
277
3
                return cast_set<uint32_t>(partition.load_tablet_idx % partition.num_buckets);
278
3
            };
279
3
        }
280
281
14
        if (partition_tablets_buffer == nullptr) {
282
14
            for (auto index : indexes) {
283
14
                tablet_indexes[index] = compute_function(block, index, *partitions[index]);
284
14
            }
285
11
        } else { // use buffer
286
6
            for (auto index : indexes) {
287
6
                auto* partition = partitions[index];
288
6
                if (auto it = partition_tablets_buffer->find(partition);
289
6
                    it != partition_tablets_buffer->end()) {
290
3
                    tablet_indexes[index] = cast_set<uint32_t>(it->second); // tablet
291
3
                } else {
292
                    // compute and save in buffer
293
3
                    (*partition_tablets_buffer)[partition] = tablet_indexes[index] =
294
3
                            compute_function(block, index, *partitions[index]);
295
3
                }
296
6
            }
297
3
        }
298
14
    }
299
300
0
    const std::vector<VOlapTablePartition*>& get_partitions() const { return _partitions; }
301
302
    // it's same with auto now because we only support transformed partition in auto partition. may expand in future
303
9
    bool is_projection_partition() const { return _is_auto_partition; }
304
19
    bool is_auto_partition() const { return _is_auto_partition; }
305
306
9
    bool is_auto_detect_overwrite() const { return _is_auto_detect_overwrite; }
307
2
    int64_t get_overwrite_group_id() const { return _overwrite_group_id; }
308
309
0
    std::shared_ptr<TNetworkAddress> get_master_address() const { return _master_address; }
310
311
2
    std::vector<uint16_t> get_partition_keys() const { return _partition_slot_locs; }
312
313
    Status add_partitions(const std::vector<TOlapTablePartition>& partitions);
314
    // no need to del/reinsert partition keys, but change the link. reset the _partitions items
315
    Status replace_partitions(std::vector<int64_t>& old_partition_ids,
316
                              const std::vector<TOlapTablePartition>& new_partitions);
317
318
13
    VExprContextSPtrs get_part_func_ctx() { return _part_func_ctx; }
319
13
    VExprSPtrs get_partition_function() { return _partition_function; }
320
321
    // which will affect _partition_block
322
    Status generate_partition_from(const TOlapTablePartition& t_part,
323
                                   VOlapTablePartition*& part_result);
324
325
2
    void set_transformed_slots(const std::vector<uint16_t>& new_slots) {
326
2
        _transformed_slot_locs = new_slots;
327
2
    }
328
329
private:
330
    Status _create_partition_keys(const std::vector<TExprNode>& t_exprs, BlockRow* part_key);
331
332
    // check if this partition contain this key
333
    bool _part_contains(VOlapTablePartition* part, BlockRowWithIndicator key) const;
334
335
    // this partition only valid in this schema
336
    std::shared_ptr<OlapTableSchemaParam> _schema;
337
    TOlapTablePartitionParam _t_param;
338
339
    const std::vector<SlotDescriptor*>& _slots;
340
    std::vector<uint16_t> _partition_slot_locs;
341
    std::vector<uint16_t> _transformed_slot_locs;
342
    std::vector<uint16_t> _distributed_slot_locs;
343
344
    ObjectPool _obj_pool;
345
    Block _partition_block;
346
    std::unique_ptr<MemTracker> _mem_tracker;
347
    std::vector<VOlapTablePartition*> _partitions;
348
    // For all partition value rows saved in this map, indicator is false. whenever we use a value to find in it, the param is true.
349
    // so that we can distinguish which column index to use (origin slots or transformed slots).
350
    // For range partition we ONLY SAVE RIGHT ENDS. when we find a part's RIGHT by a value, check if part's left cover it then.
351
    std::unique_ptr<
352
            std::map<BlockRowWithIndicator, VOlapTablePartition*, VOlapTablePartKeyComparator>>
353
            _partitions_map;
354
355
    bool _is_in_partition = false;
356
    size_t _mem_usage = 0;
357
    // only works when using list partition, the resource is owned by _partitions
358
    VOlapTablePartition* _default_partition = nullptr;
359
360
    bool _is_auto_partition = false;
361
    VExprContextSPtrs _part_func_ctx = {nullptr};
362
    VExprSPtrs _partition_function = {nullptr};
363
    TPartitionType::type _part_type; // support list or range
364
    // "insert overwrite partition(*)", detect which partitions by BE
365
    bool _is_auto_detect_overwrite = false;
366
    int64_t _overwrite_group_id = 0;
367
    std::shared_ptr<TNetworkAddress> _master_address = nullptr;
368
};
369
370
// indicate where's the tablet and all its replications (node-wise)
371
using TabletLocation = TTabletLocation;
372
// struct TTabletLocation {
373
//     1: required i64 tablet_id
374
//     2: required list<i64> node_ids
375
// }
376
377
class OlapTableLocationParam {
378
public:
379
10
    OlapTableLocationParam(const TOlapTableLocationParam& t_param) : _t_param(t_param) {
380
20
        for (auto& location : _t_param.tablets) {
381
20
            _tablets.emplace(location.tablet_id, &location);
382
20
            _update_base_to_binlog_tablet(location);
383
20
        }
384
10
    }
385
386
0
    int64_t db_id() const { return _t_param.db_id; }
387
0
    int64_t table_id() const { return _t_param.table_id; }
388
0
    int64_t version() const { return _t_param.version; }
389
390
1
    TabletLocation* find_tablet(int64_t tablet_id) const {
391
1
        auto it = _tablets.find(tablet_id);
392
1
        if (it != std::end(_tablets)) {
393
1
            return it->second;
394
1
        }
395
0
        return nullptr;
396
1
    }
397
398
    // used by base tablet on node_id to mark whether to write binlog, 0 means no binlog.
399
0
    int64_t get_binlog_tablet_id(int64_t base_tablet_id, int64_t node_id) const {
400
0
        auto it = _base_to_binlog_tablet.find({base_tablet_id, node_id});
401
0
        if (it != _base_to_binlog_tablet.end()) {
402
0
            return it->second;
403
0
        }
404
0
        if (config::is_cloud_mode()) {
405
0
            auto cloud_it = _base_to_binlog_tablet.lower_bound({base_tablet_id, INT64_MIN});
406
0
            if (cloud_it != _base_to_binlog_tablet.end() &&
407
0
                cloud_it->first.first == base_tablet_id) {
408
0
                return cloud_it->second;
409
0
            }
410
0
        }
411
0
        return 0;
412
0
    }
413
414
0
    void add_locations(std::vector<TTabletLocation>& locations) {
415
0
        for (auto& location : locations) {
416
0
            if (_tablets.find(location.tablet_id) == _tablets.end()) {
417
0
                _tablets[location.tablet_id] = &location;
418
0
            }
419
0
            _update_base_to_binlog_tablet(location);
420
0
        }
421
0
    }
422
423
private:
424
20
    void _update_base_to_binlog_tablet(const TTabletLocation& location) {
425
20
        if (!location.__isset.base_tablet_id) {
426
20
            return;
427
20
        }
428
        // the binlog tablet is written by its base tablet on the nodes that own both.
429
0
        for (int64_t node_id : location.node_ids) {
430
0
            _base_to_binlog_tablet.emplace(std::make_pair(location.base_tablet_id, node_id),
431
0
                                           location.tablet_id);
432
0
        }
433
0
    }
434
435
    TOlapTableLocationParam _t_param;
436
    // [tablet_id, tablet]. tablet has id, also.
437
    std::unordered_map<int64_t, TabletLocation*> _tablets;
438
    // [(base_tablet_id, node_id), row_binlog_tablet_id]
439
    std::map<std::pair<int64_t, int64_t>, int64_t> _base_to_binlog_tablet;
440
};
441
442
struct NodeInfo {
443
    int64_t id;
444
    int64_t option;
445
    std::string host;
446
    int32_t brpc_port;
447
448
0
    NodeInfo() = default;
449
450
    NodeInfo(const TNodeInfo& tnode)
451
2
            : id(tnode.id),
452
2
              option(tnode.option),
453
2
              host(tnode.host),
454
2
              brpc_port(tnode.async_internal_port) {}
455
};
456
457
class DorisNodesInfo {
458
public:
459
    DorisNodesInfo() = default;
460
2
    DorisNodesInfo(const TPaloNodesInfo& t_nodes) {
461
2
        for (const auto& node : t_nodes.nodes) {
462
2
            _nodes.emplace(node.id, node);
463
2
        }
464
2
    }
465
0
    void setNodes(const TPaloNodesInfo& t_nodes) {
466
0
        _nodes.clear();
467
0
        for (const auto& node : t_nodes.nodes) {
468
0
            _nodes.emplace(node.id, node);
469
0
        }
470
0
    }
471
0
    const NodeInfo* find_node(int64_t id) const {
472
0
        auto it = _nodes.find(id);
473
0
        if (it != std::end(_nodes)) {
474
0
            return &it->second;
475
0
        }
476
0
        return nullptr;
477
0
    }
478
479
0
    void add_nodes(const std::vector<TNodeInfo>& t_nodes) {
480
0
        for (const auto& node : t_nodes) {
481
0
            const auto* node_info = find_node(node.id);
482
0
            if (node_info == nullptr) {
483
0
                _nodes.emplace(node.id, node);
484
0
            }
485
0
        }
486
0
    }
487
488
0
    const std::unordered_map<int64_t, NodeInfo>& nodes_info() { return _nodes; }
489
490
private:
491
    std::unordered_map<int64_t, NodeInfo> _nodes;
492
};
493
494
} // namespace doris