Coverage Report

Created: 2025-07-25 04:22

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