Coverage Report

Created: 2026-10-29 13:10

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/doris/be/src/load/memtable/memtable.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 <stddef.h>
21
#include <stdint.h>
22
23
#include <cstdint>
24
#include <cstring>
25
#include <functional>
26
#include <memory>
27
#include <vector>
28
29
#include "common/status.h"
30
#include "core/arena.h"
31
#include "core/block/block.h"
32
#include "core/custom_allocator.h"
33
#include "exprs/aggregate/aggregate_function.h"
34
#include "runtime/memory/mem_tracker.h"
35
#include "runtime/thread_context.h"
36
#include "storage/partial_update_info.h"
37
#include "storage/tablet/tablet_schema.h"
38
39
namespace doris {
40
41
class Schema;
42
class SlotDescriptor;
43
class TabletSchema;
44
class TupleDescriptor;
45
enum KeysType : int;
46
47
// Active: the memtable is currently used by writer to insert into blocks
48
// Write_finished: the memtable finished write blocks and in the queue waiting for flush
49
// FLUSH: the memtable is under flushing, write segment to disk.
50
enum MemType { ACTIVE = 0, WRITE_FINISHED = 1, FLUSH = 2 };
51
52
// row pos in _input_mutable_block
53
struct RowInBlock {
54
    size_t _row_pos;
55
    char* _agg_mem = nullptr;
56
    size_t* _agg_state_offset = nullptr;
57
    bool _has_init_agg;
58
59
30.8k
    RowInBlock(size_t row = 0) : _row_pos(row), _has_init_agg(false) {}
60
61
1.03k
    void init_agg_places(char* agg_mem, size_t* agg_state_offset) {
62
1.03k
        _has_init_agg = true;
63
1.03k
        _agg_mem = agg_mem;
64
1.03k
        _agg_state_offset = agg_state_offset;
65
1.03k
    }
66
67
15.4k
    char* agg_places(size_t offset) const { return _agg_mem + _agg_state_offset[offset]; }
68
69
19.5k
    inline bool has_init_agg() const { return _has_init_agg; }
70
71
1.02k
    inline void remove_init_agg() { _has_init_agg = false; }
72
};
73
74
class Tie {
75
public:
76
    class Iter {
77
    public:
78
88
        Iter(Tie& tie) : _tie(tie), _next(tie._begin + 1) {}
79
5.21k
        size_t left() const { return _left; }
80
13.4k
        size_t right() const { return _right; }
81
82
        // return false means no more ranges
83
2.17k
        bool next() {
84
2.17k
            if (_next >= _tie._end) {
85
70
                return false;
86
70
            }
87
2.10k
            _next = _find(1, _next);
88
2.10k
            if (_next >= _tie._end) {
89
19
                return false;
90
19
            }
91
2.08k
            _left = _next - 1;
92
2.08k
            _next = _find(0, _next);
93
2.08k
            _right = _next;
94
2.08k
            return true;
95
2.10k
        }
96
97
    private:
98
4.19k
        size_t _find(uint8_t value, size_t start) {
99
4.19k
            if (start >= _tie._end) {
100
0
                return start;
101
0
            }
102
4.19k
            size_t offset = start - _tie._begin;
103
4.19k
            size_t size = _tie._end - start;
104
4.19k
            void* p = std::memchr(_tie._bits.data() + offset, value, size);
105
4.19k
            if (p == nullptr) {
106
53
                return _tie._end;
107
53
            }
108
4.13k
            return static_cast<uint8_t*>(p) - _tie._bits.data() + _tie._begin;
109
4.19k
        }
110
111
    private:
112
        Tie& _tie;
113
        size_t _left;
114
        size_t _right;
115
        size_t _next;
116
    };
117
118
public:
119
33
    Tie(size_t begin, size_t end) : _begin(begin), _end(end), _bits(end - begin, 1) {}
120
0
    uint8_t operator[](size_t i) const { return _bits[i - _begin]; }
121
10.3k
    uint8_t& operator[](size_t i) { return _bits[i - _begin]; }
122
88
    Iter iter() { return Iter(*this); }
123
124
private:
125
    const size_t _begin;
126
    const size_t _end;
127
    DorisVector<uint8_t> _bits;
128
};
129
130
class RowInBlockComparator {
131
public:
132
    RowInBlockComparator(std::shared_ptr<TabletSchema> tablet_schema)
133
41
            : _tablet_schema(tablet_schema) {}
134
    // call set_block before operator().
135
    // only first time insert block to create _input_mutable_block,
136
    // so can not Comparator of construct to set pblock
137
62
    void set_block(MutableBlock* pblock) { _pblock = pblock; }
138
    int operator()(const RowInBlock* left, const RowInBlock* right) const;
139
140
private:
141
    std::shared_ptr<TabletSchema> _tablet_schema;
142
    MutableBlock* _pblock = nullptr; //  corresponds to Memtable::_input_mutable_block
143
};
144
145
class MemTableStat {
146
public:
147
12
    MemTableStat& operator+=(const MemTableStat& stat) {
148
12
        raw_rows += stat.raw_rows;
149
12
        merged_rows += stat.merged_rows;
150
12
        sort_ns += stat.sort_ns;
151
12
        agg_ns += stat.agg_ns;
152
12
        put_into_output_ns += stat.put_into_output_ns;
153
12
        duration_ns += stat.duration_ns;
154
12
        sort_times += stat.sort_times;
155
12
        agg_times += stat.agg_times;
156
157
12
        return *this;
158
12
    }
159
160
    std::atomic<int64_t> raw_rows = 0;
161
    std::atomic<int64_t> merged_rows = 0;
162
    int64_t sort_ns = 0;
163
    int64_t agg_ns = 0;
164
    int64_t put_into_output_ns = 0;
165
    int64_t duration_ns = 0;
166
    std::atomic<int64_t> sort_times = 0;
167
    std::atomic<int64_t> agg_times = 0;
168
};
169
170
class MemTable {
171
public:
172
    MemTable(int64_t tablet_id, std::shared_ptr<TabletSchema> tablet_schema,
173
             const std::vector<SlotDescriptor*>* slot_descs, TupleDescriptor* tuple_desc,
174
             bool enable_unique_key_mow, PartialUpdateInfo* partial_update_info,
175
             const std::shared_ptr<ResourceContext>& resource_ctx);
176
    ~MemTable();
177
178
18
    int64_t tablet_id() const { return _tablet_id; }
179
100
    size_t memory_usage() const { return _mem_tracker->consumption(); }
180
    size_t get_flush_reserve_memory_size() const;
181
    // insert tuple from (row_pos) to (row_pos+num_rows)
182
    Status insert(const Block* block, const DorisVector<uint32_t>& row_idxs);
183
184
    void shrink_memtable_by_agg();
185
186
    bool need_flush() const;
187
188
    bool need_agg() const;
189
190
    Status to_block(std::unique_ptr<Block>* res);
191
192
27
    bool empty() const { return _input_mutable_block.rows() == 0; }
193
194
15
    const MemTableStat& stat() { return _stat; }
195
196
38
    std::shared_ptr<ResourceContext> resource_ctx() { return _resource_ctx; }
197
198
31
    std::shared_ptr<MemTracker> mem_tracker() { return _mem_tracker; }
199
200
12
    void set_flush_success() { _is_flush_success = true; }
201
202
0
    MemType get_mem_type() { return _mem_type; }
203
204
33
    void update_mem_type(MemType memtype) { _mem_type = memtype; }
205
206
35
    int64_t raw_rows() { return _stat.raw_rows.load(); }
207
208
private:
209
    // for vectorized
210
    template <bool has_skip_bitmap_col>
211
    void _aggregate_two_row_in_block(MutableBlock& mutable_block, RowInBlock* new_row,
212
                                     RowInBlock* row_in_skiplist);
213
214
    // Used to wrapped by to_block to do exception handle logic
215
    Status _to_block(std::unique_ptr<Block>* res);
216
217
    int64_t _adaptive_write_buffer_size() const;
218
219
private:
220
    std::atomic<MemType> _mem_type;
221
    int64_t _tablet_id;
222
    bool _enable_unique_key_mow = false;
223
    bool _is_flush_success = false;
224
    UniqueKeyUpdateModePB _partial_update_mode {UniqueKeyUpdateModePB::UPSERT};
225
    const KeysType _keys_type;
226
    std::shared_ptr<TabletSchema> _tablet_schema;
227
228
    std::shared_ptr<RowInBlockComparator> _vec_row_comparator;
229
230
    std::shared_ptr<ResourceContext> _resource_ctx;
231
232
    std::shared_ptr<MemTracker> _mem_tracker;
233
    // Only the rows will be inserted into block can allocate memory from _arena.
234
    // In this way, we can make MemTable::memory_usage() to be more accurate, and eventually
235
    // reduce the number of segment files that are generated by current load
236
    Arena _arena;
237
    int64_t _load_mem_limit = -1;
238
239
    void _init_columns_offset_by_slot_descs(const std::vector<SlotDescriptor*>* slot_descs,
240
                                            const TupleDescriptor* tuple_desc);
241
    std::vector<int> _column_offset;
242
243
    // Number of rows inserted to this memtable.
244
    // This is not the rows in this memtable, because rows may be merged
245
    // in unique or aggregate key model.
246
    MemTableStat _stat;
247
248
    //for vectorized
249
    MutableBlock _input_mutable_block;
250
    MutableBlock _output_mutable_block;
251
    size_t _last_sorted_pos = 0;
252
    size_t _last_agg_pos = 0;
253
254
    //return number of same keys
255
    size_t _sort();
256
    Status _sort_by_cluster_keys();
257
    void _sort_one_column(DorisVector<std::shared_ptr<RowInBlock>>& row_in_blocks, Tie& tie,
258
                          std::function<int(RowInBlock*, RowInBlock*)> cmp);
259
    template <bool is_final>
260
    void _finalize_one_row(RowInBlock* row, MutableBlock& mutable_block, int row_pos);
261
    void _init_row_for_agg(RowInBlock* row, MutableBlock& mutable_block);
262
    void _clear_row_agg(RowInBlock* row);
263
264
    template <bool is_final, bool has_skip_bitmap_col = false>
265
    void _aggregate();
266
267
    template <bool is_final>
268
    void _aggregate_for_flexible_partial_update_without_seq_col(
269
            MutableBlock& mutable_block,
270
            DorisVector<std::shared_ptr<RowInBlock>>& temp_row_in_blocks);
271
272
    template <bool is_final>
273
    void _aggregate_for_flexible_partial_update_with_seq_col(
274
            MutableBlock& mutable_block,
275
            DorisVector<std::shared_ptr<RowInBlock>>& temp_row_in_blocks);
276
277
    Status _put_into_output(Block& in_block);
278
    bool _is_first_insertion;
279
280
    void _init_agg_functions(const Block* block);
281
    std::vector<AggregateFunctionPtr> _agg_functions;
282
    std::vector<size_t> _offsets_of_aggregate_states;
283
    size_t _total_size_of_aggregate_states;
284
    std::unique_ptr<DorisVector<std::shared_ptr<RowInBlock>>> _row_in_blocks;
285
286
    size_t _num_columns;
287
    int32_t _seq_col_idx_in_block {-1};
288
    int32_t _skip_bitmap_col_idx {-1};
289
    int32_t _delete_sign_col_idx {-1};
290
    int32_t _delete_sign_col_unique_id {-1};
291
    int32_t _seq_col_unique_id {-1};
292
293
    bool _is_partial_update_and_auto_inc = false;
294
}; // class MemTable
295
296
} // namespace doris