Coverage Report

Created: 2026-05-20 12:50

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