Coverage Report

Created: 2026-04-11 00:05

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