Coverage Report

Created: 2026-03-15 18:01

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