Coverage Report

Created: 2026-08-14 13:23

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
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 SlotDescriptor;
42
class TabletSchema;
43
struct TabletAddRowsPayload;
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
    int64_t _row_binlog_lsn = 0;
56
    char* _agg_mem = nullptr;
57
    size_t* _agg_state_offset = nullptr;
58
    bool _has_init_agg;
59
60
804k
    RowInBlock(size_t row) : _row_pos(row), _has_init_agg(false) {}
61
    RowInBlock(size_t row, int64_t row_binlog_lsn)
62
35.8M
            : _row_pos(row), _row_binlog_lsn(row_binlog_lsn), _has_init_agg(false) {}
63
64
8.41k
    void init_agg_places(char* agg_mem, size_t* agg_state_offset) {
65
8.41k
        _has_init_agg = true;
66
8.41k
        _agg_mem = agg_mem;
67
8.41k
        _agg_state_offset = agg_state_offset;
68
8.41k
    }
69
70
449k
    char* agg_places(size_t offset) const { return _agg_mem + _agg_state_offset[offset]; }
71
72
8.09M
    inline bool has_init_agg() const { return _has_init_agg; }
73
74
8.41k
    inline void remove_init_agg() { _has_init_agg = false; }
75
};
76
77
class Tie {
78
public:
79
    class Iter {
80
    public:
81
259k
        Iter(Tie& tie) : _tie(tie), _next(tie._begin + 1) {}
82
10.8M
        size_t left() const { return _left; }
83
53.2M
        size_t right() const { return _right; }
84
85
        // return false means no more ranges
86
3.97M
        bool next() {
87
3.97M
            if (_next >= _tie._end) {
88
199k
                return false;
89
199k
            }
90
3.77M
            _next = _find(1, _next);
91
3.77M
            if (_next >= _tie._end) {
92
60.3k
                return false;
93
60.3k
            }
94
3.71M
            _left = _next - 1;
95
3.71M
            _next = _find(0, _next);
96
3.71M
            _right = _next;
97
3.71M
            return true;
98
3.77M
        }
99
100
    private:
101
7.51M
        size_t _find(uint8_t value, size_t start) {
102
7.51M
            if (start >= _tie._end) {
103
0
                return start;
104
0
            }
105
7.51M
            size_t offset = start - _tie._begin;
106
7.51M
            size_t size = _tie._end - start;
107
7.51M
            void* p = std::memchr(_tie._bits.data() + offset, value, size);
108
7.51M
            if (p == nullptr) {
109
102k
                return _tie._end;
110
102k
            }
111
7.41M
            return static_cast<uint8_t*>(p) - _tie._bits.data() + _tie._begin;
112
7.51M
        }
113
114
    private:
115
        Tie& _tie;
116
        size_t _left;
117
        size_t _right;
118
        size_t _next;
119
    };
120
121
public:
122
77.3k
    Tie(size_t begin, size_t end) : _begin(begin), _end(end) {
123
77.3k
        _bits = std::vector<uint8_t>(_end - _begin, 1);
124
77.3k
    }
125
0
    uint8_t operator[](size_t i) const { return _bits[i - _begin]; }
126
49.9M
    uint8_t& operator[](size_t i) { return _bits[i - _begin]; }
127
259k
    Iter iter() { return Iter(*this); }
128
129
private:
130
    const size_t _begin;
131
    const size_t _end;
132
    std::vector<uint8_t> _bits;
133
};
134
135
class RowInBlockComparator {
136
public:
137
    RowInBlockComparator(std::shared_ptr<TabletSchema> tablet_schema)
138
207k
            : _tablet_schema(tablet_schema) {}
139
    // call set_block before operator().
140
    // only first time insert block to create _input_mutable_block,
141
    // so can not Comparator of construct to set pblock
142
153k
    void set_block(MutableBlock* pblock) { _pblock = pblock; }
143
    int operator()(const RowInBlock* left, const RowInBlock* right) const;
144
145
private:
146
    std::shared_ptr<TabletSchema> _tablet_schema;
147
    MutableBlock* _pblock = nullptr; //  corresponds to Memtable::_input_mutable_block
148
};
149
150
class MemTableStat {
151
public:
152
75.7k
    MemTableStat& operator+=(const MemTableStat& stat) {
153
75.7k
        raw_rows += stat.raw_rows;
154
75.7k
        merged_rows += stat.merged_rows;
155
75.7k
        sort_ns += stat.sort_ns;
156
75.7k
        agg_ns += stat.agg_ns;
157
75.7k
        put_into_output_ns += stat.put_into_output_ns;
158
75.7k
        duration_ns += stat.duration_ns;
159
75.7k
        sort_times += stat.sort_times;
160
75.7k
        agg_times += stat.agg_times;
161
162
75.7k
        return *this;
163
75.7k
    }
164
165
    std::atomic<int64_t> raw_rows = 0;
166
    std::atomic<int64_t> merged_rows = 0;
167
    int64_t sort_ns = 0;
168
    int64_t agg_ns = 0;
169
    int64_t put_into_output_ns = 0;
170
    int64_t duration_ns = 0;
171
    std::atomic<int64_t> sort_times = 0;
172
    std::atomic<int64_t> agg_times = 0;
173
};
174
175
class MemTable {
176
public:
177
    MemTable(int64_t tablet_id, std::shared_ptr<TabletSchema> tablet_schema,
178
             const std::vector<SlotDescriptor*>* slot_descs, TupleDescriptor* tuple_desc,
179
             bool enable_unique_key_mow, PartialUpdateInfo* partial_update_info,
180
             const std::shared_ptr<ResourceContext>& resource_ctx,
181
             bool need_row_binlog_lsn = false);
182
    ~MemTable();
183
184
75.8k
    int64_t tablet_id() const { return _tablet_id; }
185
2.96M
    size_t memory_usage() const { return _mem_tracker->consumption(); }
186
    size_t get_flush_reserve_memory_size() const;
187
    // insert tuple from (row_pos) to (row_pos+num_rows)
188
    Status insert(const Block* block, const TabletAddRowsPayload& rows);
189
190
    void shrink_memtable_by_agg();
191
192
    bool need_flush() const;
193
194
    bool need_agg() const;
195
196
    Status to_block(std::unique_ptr<Block>* res);
197
198
3
    const DorisVector<int64_t>& row_binlog_lsns() const { return _output_row_binlog_lsns; }
199
200
208k
    bool empty() const { return _input_mutable_block.rows() == 0; }
201
202
75.7k
    const MemTableStat& stat() { return _stat; }
203
204
151k
    std::shared_ptr<ResourceContext> resource_ctx() { return _resource_ctx; }
205
206
75.8k
    std::shared_ptr<MemTracker> mem_tracker() { return _mem_tracker; }
207
208
75.7k
    void set_flush_success() { _is_flush_success = true; }
209
210
930k
    MemType get_mem_type() { return _mem_type; }
211
212
283k
    void update_mem_type(MemType memtype) { _mem_type = memtype; }
213
214
136k
    int64_t raw_rows() { return _stat.raw_rows.load(); }
215
216
private:
217
    // for vectorized
218
    template <bool has_skip_bitmap_col>
219
    void _aggregate_two_row_in_block(MutableBlock& mutable_block, RowInBlock* new_row,
220
                                     RowInBlock* row_in_skiplist);
221
222
    // Merge row-binlog LSN sidecar only when MemTable merges two RowInBlock objects.
223
    // Table models that require complex merge semantics, such as AGG tables and unique key
224
    // merge-on-read tables, do not support row-binlog LSN now and are rejected in insert().
225
    void _merge_row_binlog_lsn(RowInBlock* src_row, RowInBlock* dst_row);
226
227
    void _append_output_row_binlog_lsn(RowInBlock* row);
228
229
    void _aggregate_two_row_with_sequence_map(MutableBlock& mutable_block, RowInBlock* new_row,
230
                                              RowInBlock* row_in_skiplist);
231
232
    // Used to wrapped by to_block to do exception handle logic
233
    Status _to_block(std::unique_ptr<Block>* res);
234
235
    int64_t _adaptive_write_buffer_size() const;
236
237
private:
238
    std::atomic<MemType> _mem_type;
239
    int64_t _tablet_id;
240
    bool _enable_unique_key_mow = false;
241
    bool _is_flush_success = false;
242
    UniqueKeyUpdateModePB _partial_update_mode {UniqueKeyUpdateModePB::UPSERT};
243
    const KeysType _keys_type;
244
    std::shared_ptr<TabletSchema> _tablet_schema;
245
246
    std::shared_ptr<RowInBlockComparator> _vec_row_comparator;
247
248
    std::shared_ptr<ResourceContext> _resource_ctx;
249
250
    std::shared_ptr<MemTracker> _mem_tracker;
251
    // Only the rows will be inserted into block can allocate memory from _arena.
252
    // In this way, we can make MemTable::memory_usage() to be more accurate, and eventually
253
    // reduce the number of segment files that are generated by current load
254
    Arena _arena;
255
    int64_t _load_mem_limit = -1;
256
257
    void _init_columns_offset_by_slot_descs(const std::vector<SlotDescriptor*>* slot_descs,
258
                                            const TupleDescriptor* tuple_desc);
259
    std::vector<int> _column_offset;
260
261
    // Number of rows inserted to this memtable.
262
    // This is not the rows in this memtable, because rows may be merged
263
    // in unique or aggregate key model.
264
    MemTableStat _stat;
265
266
    //for vectorized
267
    MutableBlock _input_mutable_block;
268
    MutableBlock _output_mutable_block;
269
    DorisVector<int64_t> _output_row_binlog_lsns;
270
    bool _need_row_binlog_lsn = false;
271
    size_t _last_sorted_pos = 0;
272
    size_t _last_agg_pos = 0;
273
274
    //return number of same keys
275
    size_t _sort();
276
    Status _sort_by_cluster_keys();
277
    void _sort_one_column(DorisVector<std::shared_ptr<RowInBlock>>& row_in_blocks, Tie& tie,
278
                          std::function<int(RowInBlock*, RowInBlock*)> cmp);
279
    template <bool is_final>
280
    void _finalize_one_row(RowInBlock* row, MutableBlock& mutable_block, int row_pos);
281
    void _init_row_for_agg(RowInBlock* row, MutableBlock& mutable_block);
282
    void _clear_row_agg(RowInBlock* row);
283
284
    template <bool is_final, bool has_skip_bitmap_col = false>
285
    void _aggregate();
286
287
    template <bool is_final>
288
    void _aggregate_for_flexible_partial_update_without_seq_col(
289
            MutableBlock& mutable_block,
290
            DorisVector<std::shared_ptr<RowInBlock>>& temp_row_in_blocks);
291
292
    template <bool is_final>
293
    void _aggregate_for_flexible_partial_update_with_seq_col(
294
            MutableBlock& mutable_block,
295
            DorisVector<std::shared_ptr<RowInBlock>>& temp_row_in_blocks);
296
297
    Status _put_into_output(Block& in_block);
298
    bool _is_first_insertion;
299
300
    void _init_agg_functions(const Block* block);
301
    std::vector<AggregateFunctionPtr> _agg_functions;
302
    std::vector<size_t> _offsets_of_aggregate_states;
303
    size_t _total_size_of_aggregate_states;
304
    std::unique_ptr<DorisVector<std::shared_ptr<RowInBlock>>> _row_in_blocks;
305
306
    size_t _num_columns;
307
    int32_t _seq_col_idx_in_block {-1};
308
    int32_t _skip_bitmap_col_idx {-1};
309
    int32_t _delete_sign_col_idx {-1};
310
    int32_t _delete_sign_col_unique_id {-1};
311
    int32_t _seq_col_unique_id {-1};
312
313
    bool _is_partial_update_and_auto_inc = false;
314
}; // class MemTable
315
316
} // namespace doris