Coverage Report

Created: 2026-09-30 00:38

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/doris/be/src/load/memtable/memtable.cpp
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
#include "load/memtable/memtable.h"
19
20
#include <fmt/format.h>
21
#include <gen_cpp/olap_file.pb.h>
22
#include <pdqsort.h>
23
24
#include <algorithm>
25
#include <limits>
26
#include <string>
27
#include <vector>
28
29
#include "bvar/bvar.h"
30
#include "common/config.h"
31
#include "core/column/column.h"
32
#include "exprs/aggregate/aggregate_function_reader.h"
33
#include "exprs/aggregate/aggregate_function_simple_factory.h"
34
#include "load/memtable/memtable_memory_limiter.h"
35
#include "runtime/descriptors.h"
36
#include "runtime/exec_env.h"
37
#include "runtime/runtime_profile.h"
38
#include "runtime/thread_context.h"
39
#include "storage/olap_define.h"
40
#include "storage/tablet/tablet_schema.h"
41
#include "util/debug_points.h"
42
#include "util/stopwatch.hpp"
43
44
namespace doris {
45
#include "common/compile_check_begin.h"
46
47
bvar::Adder<int64_t> g_memtable_cnt("memtable_cnt");
48
bvar::Adder<uint64_t> g_flush_cuz_memtable_full("flush_cuz_memtable_full");
49
50
using namespace ErrorCode;
51
52
MemTable::MemTable(int64_t tablet_id, std::shared_ptr<TabletSchema> tablet_schema,
53
                   const std::vector<SlotDescriptor*>* slot_descs, TupleDescriptor* tuple_desc,
54
                   bool enable_unique_key_mow, PartialUpdateInfo* partial_update_info,
55
                   const std::shared_ptr<ResourceContext>& resource_ctx)
56
32
        : _mem_type(MemType::ACTIVE),
57
32
          _tablet_id(tablet_id),
58
32
          _enable_unique_key_mow(enable_unique_key_mow),
59
32
          _keys_type(tablet_schema->keys_type()),
60
32
          _tablet_schema(tablet_schema),
61
32
          _resource_ctx(resource_ctx),
62
32
          _is_first_insertion(true),
63
32
          _agg_functions(tablet_schema->num_columns()),
64
32
          _offsets_of_aggregate_states(tablet_schema->num_columns()),
65
32
          _total_size_of_aggregate_states(0) {
66
32
    g_memtable_cnt << 1;
67
32
    _mem_tracker = std::make_shared<MemTracker>();
68
32
    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(
69
32
            _resource_ctx->memory_context()->mem_tracker()->write_tracker());
70
32
    SCOPED_CONSUME_MEM_TRACKER(_mem_tracker);
71
32
    _vec_row_comparator = std::make_shared<RowInBlockComparator>(_tablet_schema);
72
32
    if (partial_update_info != nullptr) {
73
32
        _partial_update_mode = partial_update_info->update_mode();
74
32
        if (_partial_update_mode == UniqueKeyUpdateModePB::UPDATE_FIXED_COLUMNS) {
75
0
            if (partial_update_info->is_schema_contains_auto_inc_column &&
76
0
                !partial_update_info->is_input_columns_contains_auto_inc_column) {
77
0
                _is_partial_update_and_auto_inc = true;
78
0
            }
79
0
        }
80
32
    }
81
32
    _init_columns_offset_by_slot_descs(slot_descs, tuple_desc);
82
    // TODO: Support ZOrderComparator in the future
83
32
    _row_in_blocks = std::make_unique<DorisVector<std::shared_ptr<RowInBlock>>>();
84
32
    _load_mem_limit = MemInfo::mem_limit() * config::load_process_max_memory_limit_percent / 100;
85
32
}
86
87
void MemTable::_init_columns_offset_by_slot_descs(const std::vector<SlotDescriptor*>* slot_descs,
88
32
                                                  const TupleDescriptor* tuple_desc) {
89
184
    for (auto slot_desc : *slot_descs) {
90
184
        const auto& slots = tuple_desc->slots();
91
1.26k
        for (int j = 0; j < slots.size(); ++j) {
92
1.26k
            if (slot_desc->id() == slots[j]->id()) {
93
184
                _column_offset.emplace_back(j);
94
184
                break;
95
184
            }
96
1.26k
        }
97
184
    }
98
32
    if (_is_partial_update_and_auto_inc) {
99
0
        _column_offset.emplace_back(_column_offset.size());
100
0
    }
101
32
    _num_columns = _column_offset.size();
102
32
}
103
104
24
void MemTable::_init_agg_functions(const Block* block) {
105
24
    if (_num_columns > _column_offset.size()) [[unlikely]] {
106
0
        throw doris::Exception(doris::ErrorCode::INTERNAL_ERROR,
107
0
                               "num_columns {} is greater than block columns {}", _num_columns,
108
0
                               _column_offset.size());
109
0
    }
110
84
    for (auto cid = _tablet_schema->num_key_columns(); cid < _num_columns; ++cid) {
111
60
        AggregateFunctionPtr function;
112
60
        if (_keys_type == KeysType::UNIQUE_KEYS && _enable_unique_key_mow) {
113
            // In such table, non-key column's aggregation type is NONE, so we need to construct
114
            // the aggregate function manually.
115
18
            if (_skip_bitmap_col_idx != cid) {
116
18
                function = AggregateFunctionSimpleFactory::instance().get(
117
18
                        "replace_load", {block->get_data_type(cid)}, block->get_data_type(cid),
118
18
                        block->get_data_type(cid)->is_nullable(),
119
18
                        BeExecVersionManager::get_newest_version());
120
18
            } else {
121
0
                function = AggregateFunctionSimpleFactory::instance().get(
122
0
                        "bitmap_intersect", {block->get_data_type(cid)}, block->get_data_type(cid),
123
0
                        false, BeExecVersionManager::get_newest_version());
124
0
            }
125
42
        } else {
126
42
            function = _tablet_schema->column(cid).get_aggregate_function(
127
42
                    AGG_LOAD_SUFFIX, _tablet_schema->column(cid).get_be_exec_version(),
128
42
                    block->get_data_type(cid));
129
42
            if (function == nullptr) {
130
0
                LOG(WARNING) << "column get aggregate function failed, column="
131
0
                             << _tablet_schema->column(cid).name();
132
0
            }
133
42
        }
134
135
60
        DCHECK(function != nullptr);
136
60
        _agg_functions[cid] = function;
137
60
    }
138
139
84
    for (auto cid = _tablet_schema->num_key_columns(); cid < _num_columns; ++cid) {
140
60
        _offsets_of_aggregate_states[cid] = _total_size_of_aggregate_states;
141
60
        _total_size_of_aggregate_states += _agg_functions[cid]->size_of_data();
142
143
        // If not the last aggregate_state, we need pad it so that next aggregate_state will be aligned.
144
60
        if (cid + 1 < _num_columns) {
145
44
            size_t alignment_of_next_state = _agg_functions[cid + 1]->align_of_data();
146
147
            /// Extend total_size to next alignment requirement
148
            /// Add padding by rounding up 'total_size_of_aggregate_states' to be a multiplier of alignment_of_next_state.
149
44
            _total_size_of_aggregate_states =
150
44
                    (_total_size_of_aggregate_states + alignment_of_next_state - 1) /
151
44
                    alignment_of_next_state * alignment_of_next_state;
152
44
        }
153
60
    }
154
24
}
155
156
32
MemTable::~MemTable() {
157
32
    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(
158
32
            _resource_ctx->memory_context()->mem_tracker()->write_tracker());
159
32
    {
160
32
        SCOPED_CONSUME_MEM_TRACKER(_mem_tracker);
161
32
        g_memtable_cnt << -1;
162
32
        if (_keys_type != KeysType::DUP_KEYS) {
163
70
            for (auto it = _row_in_blocks->begin(); it != _row_in_blocks->end(); it++) {
164
40
                if (!(*it)->has_init_agg()) {
165
40
                    continue;
166
40
                }
167
                // We should release agg_places here, because they are not released when a
168
                // load is canceled.
169
0
                for (size_t i = _tablet_schema->num_key_columns(); i < _num_columns; ++i) {
170
0
                    auto function = _agg_functions[i];
171
0
                    DCHECK(function != nullptr);
172
0
                    function->destroy((*it)->agg_places(i));
173
0
                }
174
0
            }
175
30
        }
176
177
32
        _arena.clear(true);
178
32
        _vec_row_comparator.reset();
179
32
        _row_in_blocks.reset();
180
32
        _agg_functions.clear();
181
32
        _input_mutable_block.clear();
182
32
        _output_mutable_block.clear();
183
32
    }
184
32
    if (_is_flush_success) {
185
        // If the memtable is flush success, then its memtracker's consumption should be 0
186
24
        if (_mem_tracker->consumption() != 0 && config::crash_in_memory_tracker_inaccurate) {
187
0
            LOG(FATAL) << "memtable flush success but cosumption is not 0, it is "
188
0
                       << _mem_tracker->consumption();
189
0
        }
190
24
    }
191
32
}
192
193
12
int RowInBlockComparator::operator()(const RowInBlock* left, const RowInBlock* right) const {
194
12
    return _pblock->compare_at(left->_row_pos, right->_row_pos, _tablet_schema->num_key_columns(),
195
12
                               *_pblock, -1);
196
12
}
197
198
42
Status MemTable::insert(const Block* input_block, const DorisVector<uint32_t>& row_idxs) {
199
42
    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(
200
42
            _resource_ctx->memory_context()->mem_tracker()->write_tracker());
201
42
    SCOPED_CONSUME_MEM_TRACKER(_mem_tracker);
202
203
42
    if (_is_first_insertion) {
204
26
        _is_first_insertion = false;
205
26
        auto clone_block = input_block->clone_without_columns(&_column_offset);
206
26
        _input_mutable_block = MutableBlock::build_mutable_block(std::move(clone_block));
207
26
        _vec_row_comparator->set_block(&_input_mutable_block);
208
26
        clone_block = input_block->clone_without_columns(&_column_offset);
209
26
        _output_mutable_block = MutableBlock::build_mutable_block(std::move(clone_block));
210
26
        if (_tablet_schema->has_sequence_col()) {
211
14
            if (_partial_update_mode == UniqueKeyUpdateModePB::UPDATE_FIXED_COLUMNS) {
212
                // for unique key fixed partial update, sequence column index in block
213
                // may be different with the index in `_tablet_schema`
214
0
                for (int32_t i = 0; i < clone_block.columns(); i++) {
215
0
                    if (clone_block.get_by_position(i).name == SEQUENCE_COL) {
216
0
                        _seq_col_idx_in_block = i;
217
0
                        break;
218
0
                    }
219
0
                }
220
14
            } else {
221
14
                _seq_col_idx_in_block = _tablet_schema->sequence_col_idx();
222
14
            }
223
14
        }
224
26
        if (_partial_update_mode == UniqueKeyUpdateModePB::UPDATE_FLEXIBLE_COLUMNS &&
225
26
            _tablet_schema->has_skip_bitmap_col()) {
226
            // init of _skip_bitmap_col_idx and _delete_sign_col_idx must be before _init_agg_functions()
227
0
            _skip_bitmap_col_idx = _tablet_schema->skip_bitmap_col_idx();
228
0
            _delete_sign_col_idx = _tablet_schema->delete_sign_idx();
229
0
            _delete_sign_col_unique_id = _tablet_schema->column(_delete_sign_col_idx).unique_id();
230
0
            if (_seq_col_idx_in_block != -1) {
231
0
                _seq_col_unique_id = _tablet_schema->column(_seq_col_idx_in_block).unique_id();
232
0
            }
233
0
        }
234
26
        if (_keys_type != KeysType::DUP_KEYS) {
235
            // there may be additional intermediate columns in input_block
236
            // we only need columns indicated by column offset in the output
237
24
            RETURN_IF_CATCH_EXCEPTION(_init_agg_functions(&clone_block));
238
24
        }
239
26
    }
240
241
42
    auto num_rows = row_idxs.size();
242
42
    size_t cursor_in_mutableblock = _input_mutable_block.rows();
243
42
    RETURN_IF_ERROR(_input_mutable_block.add_rows(input_block, row_idxs.data(),
244
42
                                                  row_idxs.data() + num_rows, &_column_offset));
245
84
    for (int i = 0; i < num_rows; i++) {
246
42
        _row_in_blocks->emplace_back(std::make_shared<RowInBlock>(cursor_in_mutableblock + i));
247
42
    }
248
249
42
    _stat.raw_rows += num_rows;
250
42
    return Status::OK();
251
42
}
252
253
template <bool has_skip_bitmap_col>
254
void MemTable::_aggregate_two_row_in_block(MutableBlock& mutable_block, RowInBlock* src_row,
255
6
                                           RowInBlock* dst_row) {
256
    // for flexible partial update, the caller must guarantees that either src_row and dst_row
257
    // both specify the sequence column, or src_row and dst_row both don't specify the
258
    // sequence column
259
6
    if (_tablet_schema->has_sequence_col() && _seq_col_idx_in_block >= 0) {
260
6
        DCHECK_LT(_seq_col_idx_in_block, mutable_block.columns());
261
6
        auto col_ptr = mutable_block.mutable_columns()[_seq_col_idx_in_block].get();
262
6
        auto res = col_ptr->compare_at(dst_row->_row_pos, src_row->_row_pos, *col_ptr, -1);
263
        // dst sequence column larger than src, don't need to update
264
6
        if (res > 0) {
265
6
            return;
266
6
        }
267
        // need to update the row pos in dst row to the src row pos when has
268
        // sequence column
269
0
        dst_row->_row_pos = src_row->_row_pos;
270
0
    }
271
    // dst is non-sequence row, or dst sequence is smaller
272
0
    if constexpr (!has_skip_bitmap_col) {
273
0
        DCHECK(_skip_bitmap_col_idx == -1);
274
0
        for (size_t cid = _tablet_schema->num_key_columns(); cid < _num_columns; ++cid) {
275
0
            auto* col_ptr = mutable_block.mutable_columns()[cid].get();
276
0
            _agg_functions[cid]->add(dst_row->agg_places(cid),
277
0
                                     const_cast<const doris::IColumn**>(&col_ptr),
278
0
                                     src_row->_row_pos, _arena);
279
0
        }
280
0
    } else {
281
0
        DCHECK(_skip_bitmap_col_idx != -1);
282
0
        DCHECK_LT(_skip_bitmap_col_idx, mutable_block.columns());
283
0
        const BitmapValue& skip_bitmap =
284
0
                assert_cast<ColumnBitmap*, TypeCheckOnRelease::DISABLE>(
285
0
                        mutable_block.mutable_columns()[_skip_bitmap_col_idx].get())
286
0
                        ->get_data()[src_row->_row_pos];
287
0
        for (size_t cid = _tablet_schema->num_key_columns(); cid < _num_columns; ++cid) {
288
0
            const auto& col = _tablet_schema->column(cid);
289
0
            if (cid != _skip_bitmap_col_idx && skip_bitmap.contains(col.unique_id())) {
290
0
                continue;
291
0
            }
292
0
            auto* col_ptr = mutable_block.mutable_columns()[cid].get();
293
0
            _agg_functions[cid]->add(dst_row->agg_places(cid),
294
0
                                     const_cast<const doris::IColumn**>(&col_ptr),
295
0
                                     src_row->_row_pos, _arena);
296
0
        }
297
0
    }
298
0
}
_ZN5doris8MemTable27_aggregate_two_row_in_blockILb0EEEvRNS_12MutableBlockEPNS_10RowInBlockES5_
Line
Count
Source
255
6
                                           RowInBlock* dst_row) {
256
    // for flexible partial update, the caller must guarantees that either src_row and dst_row
257
    // both specify the sequence column, or src_row and dst_row both don't specify the
258
    // sequence column
259
6
    if (_tablet_schema->has_sequence_col() && _seq_col_idx_in_block >= 0) {
260
6
        DCHECK_LT(_seq_col_idx_in_block, mutable_block.columns());
261
6
        auto col_ptr = mutable_block.mutable_columns()[_seq_col_idx_in_block].get();
262
6
        auto res = col_ptr->compare_at(dst_row->_row_pos, src_row->_row_pos, *col_ptr, -1);
263
        // dst sequence column larger than src, don't need to update
264
6
        if (res > 0) {
265
6
            return;
266
6
        }
267
        // need to update the row pos in dst row to the src row pos when has
268
        // sequence column
269
0
        dst_row->_row_pos = src_row->_row_pos;
270
0
    }
271
    // dst is non-sequence row, or dst sequence is smaller
272
0
    if constexpr (!has_skip_bitmap_col) {
273
0
        DCHECK(_skip_bitmap_col_idx == -1);
274
0
        for (size_t cid = _tablet_schema->num_key_columns(); cid < _num_columns; ++cid) {
275
0
            auto* col_ptr = mutable_block.mutable_columns()[cid].get();
276
0
            _agg_functions[cid]->add(dst_row->agg_places(cid),
277
0
                                     const_cast<const doris::IColumn**>(&col_ptr),
278
0
                                     src_row->_row_pos, _arena);
279
0
        }
280
    } else {
281
        DCHECK(_skip_bitmap_col_idx != -1);
282
        DCHECK_LT(_skip_bitmap_col_idx, mutable_block.columns());
283
        const BitmapValue& skip_bitmap =
284
                assert_cast<ColumnBitmap*, TypeCheckOnRelease::DISABLE>(
285
                        mutable_block.mutable_columns()[_skip_bitmap_col_idx].get())
286
                        ->get_data()[src_row->_row_pos];
287
        for (size_t cid = _tablet_schema->num_key_columns(); cid < _num_columns; ++cid) {
288
            const auto& col = _tablet_schema->column(cid);
289
            if (cid != _skip_bitmap_col_idx && skip_bitmap.contains(col.unique_id())) {
290
                continue;
291
            }
292
            auto* col_ptr = mutable_block.mutable_columns()[cid].get();
293
            _agg_functions[cid]->add(dst_row->agg_places(cid),
294
                                     const_cast<const doris::IColumn**>(&col_ptr),
295
                                     src_row->_row_pos, _arena);
296
        }
297
    }
298
0
}
Unexecuted instantiation: _ZN5doris8MemTable27_aggregate_two_row_in_blockILb1EEEvRNS_12MutableBlockEPNS_10RowInBlockES5_
299
18
Status MemTable::_put_into_output(Block& in_block) {
300
18
    SCOPED_RAW_TIMER(&_stat.put_into_output_ns);
301
18
    DorisVector<uint32_t> row_pos_vec;
302
18
    DCHECK(in_block.rows() <= std::numeric_limits<int>::max());
303
18
    row_pos_vec.reserve(in_block.rows());
304
40
    for (int i = 0; i < _row_in_blocks->size(); i++) {
305
22
        row_pos_vec.emplace_back((*_row_in_blocks)[i]->_row_pos);
306
22
    }
307
18
    return _output_mutable_block.add_rows(&in_block, row_pos_vec.data(),
308
18
                                          row_pos_vec.data() + in_block.rows());
309
18
}
310
311
24
size_t MemTable::_sort() {
312
24
    SCOPED_RAW_TIMER(&_stat.sort_ns);
313
24
    _stat.sort_times++;
314
24
    size_t same_keys_num = 0;
315
    // sort new rows
316
24
    Tie tie = Tie(_last_sorted_pos, _row_in_blocks->size());
317
86
    for (size_t i = 0; i < _tablet_schema->num_key_columns(); i++) {
318
62
        auto cmp = [&](RowInBlock* lhs, RowInBlock* rhs) -> int {
319
60
            return _input_mutable_block.compare_one_column(lhs->_row_pos, rhs->_row_pos, i, -1);
320
60
        };
321
62
        _sort_one_column(*_row_in_blocks, tie, cmp);
322
62
    }
323
24
    bool is_dup = (_keys_type == KeysType::DUP_KEYS);
324
    // sort extra round by _row_pos to make the sort stable
325
24
    auto iter = tie.iter();
326
30
    while (iter.next()) {
327
6
        pdqsort(std::next(_row_in_blocks->begin(), iter.left()),
328
6
                std::next(_row_in_blocks->begin(), iter.right()),
329
6
                [&is_dup](const std::shared_ptr<RowInBlock>& lhs,
330
6
                          const std::shared_ptr<RowInBlock>& rhs) -> bool {
331
6
                    return is_dup ? lhs->_row_pos > rhs->_row_pos : lhs->_row_pos < rhs->_row_pos;
332
6
                });
333
6
        same_keys_num += iter.right() - iter.left();
334
6
    }
335
    // merge new rows and old rows
336
24
    _vec_row_comparator->set_block(&_input_mutable_block);
337
24
    auto cmp_func = [this, is_dup, &same_keys_num](const std::shared_ptr<RowInBlock>& l,
338
24
                                                   const std::shared_ptr<RowInBlock>& r) -> bool {
339
0
        auto value = (*(this->_vec_row_comparator))(l.get(), r.get());
340
0
        if (value == 0) {
341
0
            same_keys_num++;
342
0
            return is_dup ? l->_row_pos > r->_row_pos : l->_row_pos < r->_row_pos;
343
0
        } else {
344
0
            return value < 0;
345
0
        }
346
0
    };
347
24
    auto new_row_it = std::next(_row_in_blocks->begin(), _last_sorted_pos);
348
24
    std::inplace_merge(_row_in_blocks->begin(), new_row_it, _row_in_blocks->end(), cmp_func);
349
24
    _last_sorted_pos = _row_in_blocks->size();
350
24
    return same_keys_num;
351
24
}
352
353
2
Status MemTable::_sort_by_cluster_keys() {
354
2
    SCOPED_RAW_TIMER(&_stat.sort_ns);
355
2
    _stat.sort_times++;
356
    // sort all rows
357
2
    Block in_block = _output_mutable_block.to_block();
358
2
    auto clone_block = in_block.clone_without_columns();
359
2
    MutableBlock mutable_block = MutableBlock::build_mutable_block(std::move(in_block));
360
2
    _output_mutable_block = MutableBlock::build_mutable_block(std::move(clone_block));
361
362
2
    DorisVector<std::shared_ptr<RowInBlock>> row_in_blocks;
363
2
    row_in_blocks.reserve(mutable_block.rows());
364
10
    for (size_t i = 0; i < mutable_block.rows(); i++) {
365
8
        row_in_blocks.emplace_back(std::make_shared<RowInBlock>(i));
366
8
    }
367
2
    Tie tie = Tie(0, mutable_block.rows());
368
369
4
    for (auto cid : _tablet_schema->cluster_key_uids()) {
370
4
        auto index = _tablet_schema->field_index(cid);
371
4
        if (index == -1) {
372
0
            return Status::InternalError("could not find cluster key column with unique_id=" +
373
0
                                         std::to_string(cid) + " in tablet schema");
374
0
        }
375
16
        auto cmp = [&](const RowInBlock* lhs, const RowInBlock* rhs) -> int {
376
16
            return mutable_block.compare_one_column(lhs->_row_pos, rhs->_row_pos, index, -1);
377
16
        };
378
4
        _sort_one_column(row_in_blocks, tie, cmp);
379
4
    }
380
381
    // sort extra round by _row_pos to make the sort stable
382
2
    auto iter = tie.iter();
383
2
    while (iter.next()) {
384
0
        pdqsort(std::next(row_in_blocks.begin(), iter.left()),
385
0
                std::next(row_in_blocks.begin(), iter.right()),
386
0
                [](const std::shared_ptr<RowInBlock>& lhs, const std::shared_ptr<RowInBlock>& rhs)
387
0
                        -> bool { return lhs->_row_pos < rhs->_row_pos; });
388
0
    }
389
390
2
    in_block = mutable_block.to_block();
391
2
    SCOPED_RAW_TIMER(&_stat.put_into_output_ns);
392
2
    DorisVector<uint32_t> row_pos_vec;
393
2
    DCHECK(in_block.rows() <= std::numeric_limits<int>::max());
394
2
    row_pos_vec.reserve(in_block.rows());
395
10
    for (int i = 0; i < row_in_blocks.size(); i++) {
396
8
        row_pos_vec.emplace_back(row_in_blocks[i]->_row_pos);
397
8
    }
398
2
    std::vector<int> column_offset;
399
12
    for (int i = 0; i < _column_offset.size(); ++i) {
400
10
        column_offset.emplace_back(i);
401
10
    }
402
2
    return _output_mutable_block.add_rows(&in_block, row_pos_vec.data(),
403
2
                                          row_pos_vec.data() + in_block.rows(), &column_offset);
404
2
}
405
406
void MemTable::_sort_one_column(DorisVector<std::shared_ptr<RowInBlock>>& row_in_blocks, Tie& tie,
407
66
                                std::function<int(RowInBlock*, RowInBlock*)> cmp) {
408
66
    auto iter = tie.iter();
409
86
    while (iter.next()) {
410
20
        pdqsort(std::next(row_in_blocks.begin(), static_cast<int>(iter.left())),
411
20
                std::next(row_in_blocks.begin(), static_cast<int>(iter.right())),
412
42
                [&cmp](auto lhs, auto rhs) -> bool { return cmp(lhs.get(), rhs.get()) < 0; });
413
20
        tie[iter.left()] = 0;
414
54
        for (auto i = iter.left() + 1; i < iter.right(); i++) {
415
34
            tie[i] = (cmp(row_in_blocks[i - 1].get(), row_in_blocks[i].get()) == 0);
416
34
        }
417
20
    }
418
66
}
419
420
template <bool is_final>
421
12
void MemTable::_finalize_one_row(RowInBlock* row, MutableBlock& mutable_block, int row_pos) {
422
    // move key columns
423
36
    for (size_t i = 0; i < _tablet_schema->num_key_columns(); ++i) {
424
24
        _output_mutable_block.get_column_by_position(i)->insert_from(
425
24
                *mutable_block.get_column_by_position(i), row->_row_pos);
426
24
    }
427
12
    if (row->has_init_agg()) {
428
        // get value columns from agg_places
429
24
        for (size_t i = _tablet_schema->num_key_columns(); i < _num_columns; ++i) {
430
18
            auto function = _agg_functions[i];
431
18
            auto* agg_place = row->agg_places(i);
432
18
            auto* col_ptr = _output_mutable_block.get_column_by_position(i).get();
433
18
            function->insert_result_into(agg_place, *col_ptr);
434
435
18
            if constexpr (is_final) {
436
18
                function->destroy(agg_place);
437
18
            } else {
438
0
                function->reset(agg_place);
439
0
            }
440
18
        }
441
442
6
        if constexpr (is_final) {
443
6
            row->remove_init_agg();
444
6
        } else {
445
0
            for (size_t i = _tablet_schema->num_key_columns(); i < _num_columns; ++i) {
446
0
                auto function = _agg_functions[i];
447
0
                auto* agg_place = row->agg_places(i);
448
0
                auto* col_ptr = _output_mutable_block.get_column_by_position(i).get();
449
0
                function->add(agg_place, const_cast<const doris::IColumn**>(&col_ptr), row_pos,
450
0
                              _arena);
451
0
            }
452
0
        }
453
6
    } else {
454
        // move columns for rows do not need agg
455
24
        for (size_t i = _tablet_schema->num_key_columns(); i < _num_columns; ++i) {
456
18
            _output_mutable_block.get_column_by_position(i)->insert_from(
457
18
                    *mutable_block.get_column_by_position(i), row->_row_pos);
458
18
        }
459
6
    }
460
12
    if constexpr (!is_final) {
461
0
        row->_row_pos = row_pos;
462
0
    }
463
12
}
Unexecuted instantiation: _ZN5doris8MemTable17_finalize_one_rowILb0EEEvPNS_10RowInBlockERNS_12MutableBlockEi
_ZN5doris8MemTable17_finalize_one_rowILb1EEEvPNS_10RowInBlockERNS_12MutableBlockEi
Line
Count
Source
421
12
void MemTable::_finalize_one_row(RowInBlock* row, MutableBlock& mutable_block, int row_pos) {
422
    // move key columns
423
36
    for (size_t i = 0; i < _tablet_schema->num_key_columns(); ++i) {
424
24
        _output_mutable_block.get_column_by_position(i)->insert_from(
425
24
                *mutable_block.get_column_by_position(i), row->_row_pos);
426
24
    }
427
12
    if (row->has_init_agg()) {
428
        // get value columns from agg_places
429
24
        for (size_t i = _tablet_schema->num_key_columns(); i < _num_columns; ++i) {
430
18
            auto function = _agg_functions[i];
431
18
            auto* agg_place = row->agg_places(i);
432
18
            auto* col_ptr = _output_mutable_block.get_column_by_position(i).get();
433
18
            function->insert_result_into(agg_place, *col_ptr);
434
435
18
            if constexpr (is_final) {
436
18
                function->destroy(agg_place);
437
            } else {
438
                function->reset(agg_place);
439
            }
440
18
        }
441
442
6
        if constexpr (is_final) {
443
6
            row->remove_init_agg();
444
        } else {
445
            for (size_t i = _tablet_schema->num_key_columns(); i < _num_columns; ++i) {
446
                auto function = _agg_functions[i];
447
                auto* agg_place = row->agg_places(i);
448
                auto* col_ptr = _output_mutable_block.get_column_by_position(i).get();
449
                function->add(agg_place, const_cast<const doris::IColumn**>(&col_ptr), row_pos,
450
                              _arena);
451
            }
452
        }
453
6
    } else {
454
        // move columns for rows do not need agg
455
24
        for (size_t i = _tablet_schema->num_key_columns(); i < _num_columns; ++i) {
456
18
            _output_mutable_block.get_column_by_position(i)->insert_from(
457
18
                    *mutable_block.get_column_by_position(i), row->_row_pos);
458
18
        }
459
6
    }
460
    if constexpr (!is_final) {
461
        row->_row_pos = row_pos;
462
    }
463
12
}
464
465
6
void MemTable::_init_row_for_agg(RowInBlock* row, MutableBlock& mutable_block) {
466
6
    row->init_agg_places(_arena.aligned_alloc(_total_size_of_aggregate_states, 16),
467
6
                         _offsets_of_aggregate_states.data());
468
24
    for (auto cid = _tablet_schema->num_key_columns(); cid < _num_columns; cid++) {
469
18
        auto* col_ptr = mutable_block.mutable_columns()[cid].get();
470
18
        auto* data = row->agg_places(cid);
471
18
        _agg_functions[cid]->create(data);
472
18
        _agg_functions[cid]->add(data, const_cast<const doris::IColumn**>(&col_ptr), row->_row_pos,
473
18
                                 _arena);
474
18
    }
475
6
}
476
6
void MemTable::_clear_row_agg(RowInBlock* row) {
477
6
    if (row->has_init_agg()) {
478
0
        for (size_t i = _tablet_schema->num_key_columns(); i < _num_columns; ++i) {
479
0
            auto function = _agg_functions[i];
480
0
            auto* agg_place = row->agg_places(i);
481
0
            function->destroy(agg_place);
482
0
        }
483
0
        row->remove_init_agg();
484
0
    }
485
6
}
486
// only in `to_block` the `is_final` flag will be true, in other cases, it will be false
487
template <bool is_final, bool has_skip_bitmap_col>
488
6
void MemTable::_aggregate() {
489
6
    SCOPED_RAW_TIMER(&_stat.agg_ns);
490
6
    _stat.agg_times++;
491
6
    Block in_block = _input_mutable_block.to_block();
492
6
    std::unique_ptr<Block> empty_input_block = in_block.create_same_struct_block(0);
493
6
    MutableBlock mutable_block = MutableBlock::build_mutable_block(std::move(in_block));
494
6
    _vec_row_comparator->set_block(&mutable_block);
495
6
    DorisVector<std::shared_ptr<RowInBlock>> temp_row_in_blocks;
496
6
    temp_row_in_blocks.reserve(_last_sorted_pos);
497
    //only init agg if needed
498
499
6
    if constexpr (!has_skip_bitmap_col) {
500
6
        RowInBlock* prev_row = nullptr;
501
6
        int row_pos = -1;
502
18
        for (const auto& cur_row_ptr : *_row_in_blocks) {
503
18
            RowInBlock* cur_row = cur_row_ptr.get();
504
18
            if (!temp_row_in_blocks.empty() && (*_vec_row_comparator)(prev_row, cur_row) == 0) {
505
6
                if (!prev_row->has_init_agg()) {
506
6
                    _init_row_for_agg(prev_row, mutable_block);
507
6
                }
508
6
                _stat.merged_rows++;
509
6
                _aggregate_two_row_in_block<has_skip_bitmap_col>(mutable_block, cur_row, prev_row);
510
                // Clean up aggregation state of the merged row to avoid memory leak
511
6
                _clear_row_agg(cur_row);
512
12
            } else {
513
12
                prev_row = cur_row;
514
12
                if (!temp_row_in_blocks.empty()) {
515
                    // The rows from the previous batch of _row_in_blocks have been merged into
516
                    // temp_row_in_blocks, now finalize into the mutable block.
517
6
                    _finalize_one_row<is_final>(temp_row_in_blocks.back().get(), mutable_block,
518
6
                                                row_pos);
519
6
                }
520
12
                temp_row_in_blocks.push_back(cur_row_ptr);
521
12
                row_pos++;
522
12
            }
523
18
        }
524
6
        if (!temp_row_in_blocks.empty()) {
525
            // finalize the last low
526
6
            _finalize_one_row<is_final>(temp_row_in_blocks.back().get(), mutable_block, row_pos);
527
6
        }
528
6
    } else {
529
0
        DCHECK(_delete_sign_col_idx != -1);
530
0
        if (_seq_col_idx_in_block == -1) {
531
0
            _aggregate_for_flexible_partial_update_without_seq_col<is_final>(mutable_block,
532
0
                                                                             temp_row_in_blocks);
533
0
        } else {
534
0
            _aggregate_for_flexible_partial_update_with_seq_col<is_final>(mutable_block,
535
0
                                                                          temp_row_in_blocks);
536
0
        }
537
0
    }
538
6
    if constexpr (!is_final) {
539
        // if is not final, we collect the agg results to input_block and then continue to insert
540
0
        _input_mutable_block.swap(_output_mutable_block);
541
        //TODO(weixang):opt here.
542
0
        _output_mutable_block = MutableBlock::build_mutable_block(std::move(*empty_input_block));
543
0
        _output_mutable_block.clear_column_data();
544
0
        *_row_in_blocks = temp_row_in_blocks;
545
0
        _last_sorted_pos = _row_in_blocks->size();
546
0
    }
547
6
}
Unexecuted instantiation: _ZN5doris8MemTable10_aggregateILb0ELb0EEEvv
Unexecuted instantiation: _ZN5doris8MemTable10_aggregateILb0ELb1EEEvv
_ZN5doris8MemTable10_aggregateILb1ELb0EEEvv
Line
Count
Source
488
6
void MemTable::_aggregate() {
489
6
    SCOPED_RAW_TIMER(&_stat.agg_ns);
490
6
    _stat.agg_times++;
491
6
    Block in_block = _input_mutable_block.to_block();
492
6
    std::unique_ptr<Block> empty_input_block = in_block.create_same_struct_block(0);
493
6
    MutableBlock mutable_block = MutableBlock::build_mutable_block(std::move(in_block));
494
6
    _vec_row_comparator->set_block(&mutable_block);
495
6
    DorisVector<std::shared_ptr<RowInBlock>> temp_row_in_blocks;
496
6
    temp_row_in_blocks.reserve(_last_sorted_pos);
497
    //only init agg if needed
498
499
6
    if constexpr (!has_skip_bitmap_col) {
500
6
        RowInBlock* prev_row = nullptr;
501
6
        int row_pos = -1;
502
18
        for (const auto& cur_row_ptr : *_row_in_blocks) {
503
18
            RowInBlock* cur_row = cur_row_ptr.get();
504
18
            if (!temp_row_in_blocks.empty() && (*_vec_row_comparator)(prev_row, cur_row) == 0) {
505
6
                if (!prev_row->has_init_agg()) {
506
6
                    _init_row_for_agg(prev_row, mutable_block);
507
6
                }
508
6
                _stat.merged_rows++;
509
6
                _aggregate_two_row_in_block<has_skip_bitmap_col>(mutable_block, cur_row, prev_row);
510
                // Clean up aggregation state of the merged row to avoid memory leak
511
6
                _clear_row_agg(cur_row);
512
12
            } else {
513
12
                prev_row = cur_row;
514
12
                if (!temp_row_in_blocks.empty()) {
515
                    // The rows from the previous batch of _row_in_blocks have been merged into
516
                    // temp_row_in_blocks, now finalize into the mutable block.
517
6
                    _finalize_one_row<is_final>(temp_row_in_blocks.back().get(), mutable_block,
518
6
                                                row_pos);
519
6
                }
520
12
                temp_row_in_blocks.push_back(cur_row_ptr);
521
12
                row_pos++;
522
12
            }
523
18
        }
524
6
        if (!temp_row_in_blocks.empty()) {
525
            // finalize the last low
526
6
            _finalize_one_row<is_final>(temp_row_in_blocks.back().get(), mutable_block, row_pos);
527
6
        }
528
    } else {
529
        DCHECK(_delete_sign_col_idx != -1);
530
        if (_seq_col_idx_in_block == -1) {
531
            _aggregate_for_flexible_partial_update_without_seq_col<is_final>(mutable_block,
532
                                                                             temp_row_in_blocks);
533
        } else {
534
            _aggregate_for_flexible_partial_update_with_seq_col<is_final>(mutable_block,
535
                                                                          temp_row_in_blocks);
536
        }
537
    }
538
    if constexpr (!is_final) {
539
        // if is not final, we collect the agg results to input_block and then continue to insert
540
        _input_mutable_block.swap(_output_mutable_block);
541
        //TODO(weixang):opt here.
542
        _output_mutable_block = MutableBlock::build_mutable_block(std::move(*empty_input_block));
543
        _output_mutable_block.clear_column_data();
544
        *_row_in_blocks = temp_row_in_blocks;
545
        _last_sorted_pos = _row_in_blocks->size();
546
    }
547
6
}
Unexecuted instantiation: _ZN5doris8MemTable10_aggregateILb1ELb1EEEvv
548
549
template <bool is_final>
550
void MemTable::_aggregate_for_flexible_partial_update_without_seq_col(
551
0
        MutableBlock& mutable_block, DorisVector<std::shared_ptr<RowInBlock>>& temp_row_in_blocks) {
552
0
    std::shared_ptr<RowInBlock> prev_row {nullptr};
553
0
    int row_pos = -1;
554
0
    auto& skip_bitmaps =
555
0
            assert_cast<ColumnBitmap*>(mutable_block.mutable_columns()[_skip_bitmap_col_idx].get())
556
0
                    ->get_data();
557
0
    auto& delete_signs =
558
0
            assert_cast<ColumnInt8*>(mutable_block.mutable_columns()[_delete_sign_col_idx].get())
559
0
                    ->get_data();
560
0
    std::shared_ptr<RowInBlock> row_with_delete_sign {nullptr};
561
0
    std::shared_ptr<RowInBlock> row_without_delete_sign {nullptr};
562
563
0
    auto finalize_rows = [&]() {
564
0
        if (row_with_delete_sign != nullptr) {
565
0
            temp_row_in_blocks.push_back(row_with_delete_sign);
566
0
            _finalize_one_row<is_final>(row_with_delete_sign.get(), mutable_block, ++row_pos);
567
0
            row_with_delete_sign = nullptr;
568
0
        }
569
0
        if (row_without_delete_sign != nullptr) {
570
0
            temp_row_in_blocks.push_back(row_without_delete_sign);
571
0
            _finalize_one_row<is_final>(row_without_delete_sign.get(), mutable_block, ++row_pos);
572
0
            row_without_delete_sign = nullptr;
573
0
        }
574
        // _arena.clear();
575
0
    };
Unexecuted instantiation: _ZZN5doris8MemTable54_aggregate_for_flexible_partial_update_without_seq_colILb0EEEvRNS_12MutableBlockERSt6vectorISt10shared_ptrINS_10RowInBlockEENS_18CustomStdAllocatorIS7_NS_9AllocatorILb0ELb0ELb0ENS_22DefaultMemoryAllocatorELb1EEEEEEENKUlvE_clEv
Unexecuted instantiation: _ZZN5doris8MemTable54_aggregate_for_flexible_partial_update_without_seq_colILb1EEEvRNS_12MutableBlockERSt6vectorISt10shared_ptrINS_10RowInBlockEENS_18CustomStdAllocatorIS7_NS_9AllocatorILb0ELb0ELb0ENS_22DefaultMemoryAllocatorELb1EEEEEEENKUlvE_clEv
576
577
0
    auto add_row = [&](std::shared_ptr<RowInBlock> row, bool with_delete_sign) {
578
0
        if (with_delete_sign) {
579
0
            row_with_delete_sign = std::move(row);
580
0
        } else {
581
0
            row_without_delete_sign = std::move(row);
582
0
        }
583
0
    };
Unexecuted instantiation: _ZZN5doris8MemTable54_aggregate_for_flexible_partial_update_without_seq_colILb0EEEvRNS_12MutableBlockERSt6vectorISt10shared_ptrINS_10RowInBlockEENS_18CustomStdAllocatorIS7_NS_9AllocatorILb0ELb0ELb0ENS_22DefaultMemoryAllocatorELb1EEEEEEENKUlS7_bE_clES7_b
Unexecuted instantiation: _ZZN5doris8MemTable54_aggregate_for_flexible_partial_update_without_seq_colILb1EEEvRNS_12MutableBlockERSt6vectorISt10shared_ptrINS_10RowInBlockEENS_18CustomStdAllocatorIS7_NS_9AllocatorILb0ELb0ELb0ENS_22DefaultMemoryAllocatorELb1EEEEEEENKUlS7_bE_clES7_b
584
0
    for (const auto& cur_row_ptr : *_row_in_blocks) {
585
0
        RowInBlock* cur_row = cur_row_ptr.get();
586
0
        const BitmapValue& skip_bitmap = skip_bitmaps[cur_row->_row_pos];
587
0
        bool cur_row_has_delete_sign = (!skip_bitmap.contains(_delete_sign_col_unique_id) &&
588
0
                                        delete_signs[cur_row->_row_pos] != 0);
589
0
        prev_row =
590
0
                (row_with_delete_sign == nullptr) ? row_without_delete_sign : row_with_delete_sign;
591
        // compare keys, the keys of row_with_delete_sign and row_without_delete_sign is the same,
592
        // choose any of them if it's valid
593
0
        if (prev_row != nullptr && (*_vec_row_comparator)(prev_row.get(), cur_row) == 0) {
594
0
            if (cur_row_has_delete_sign) {
595
0
                if (row_without_delete_sign != nullptr) {
596
                    // if there exits row without delete sign, remove it first
597
0
                    _clear_row_agg(row_without_delete_sign.get());
598
0
                    _stat.merged_rows++;
599
0
                    row_without_delete_sign = nullptr;
600
0
                }
601
                // and then unconditionally replace the previous row
602
0
                prev_row = row_with_delete_sign;
603
0
            } else {
604
0
                prev_row = row_without_delete_sign;
605
0
            }
606
607
0
            if (prev_row == nullptr) {
608
0
                add_row(cur_row_ptr, cur_row_has_delete_sign);
609
0
            } else {
610
0
                if (!prev_row->has_init_agg()) {
611
0
                    _init_row_for_agg(prev_row.get(), mutable_block);
612
0
                }
613
0
                _stat.merged_rows++;
614
0
                _aggregate_two_row_in_block<true>(mutable_block, cur_row, prev_row.get());
615
0
            }
616
0
        } else {
617
0
            finalize_rows();
618
0
            add_row(cur_row_ptr, cur_row_has_delete_sign);
619
0
        }
620
0
    }
621
    // finalize the last lows
622
0
    finalize_rows();
623
0
}
Unexecuted instantiation: _ZN5doris8MemTable54_aggregate_for_flexible_partial_update_without_seq_colILb0EEEvRNS_12MutableBlockERSt6vectorISt10shared_ptrINS_10RowInBlockEENS_18CustomStdAllocatorIS7_NS_9AllocatorILb0ELb0ELb0ENS_22DefaultMemoryAllocatorELb1EEEEEE
Unexecuted instantiation: _ZN5doris8MemTable54_aggregate_for_flexible_partial_update_without_seq_colILb1EEEvRNS_12MutableBlockERSt6vectorISt10shared_ptrINS_10RowInBlockEENS_18CustomStdAllocatorIS7_NS_9AllocatorILb0ELb0ELb0ENS_22DefaultMemoryAllocatorELb1EEEEEE
624
625
template <bool is_final>
626
void MemTable::_aggregate_for_flexible_partial_update_with_seq_col(
627
0
        MutableBlock& mutable_block, DorisVector<std::shared_ptr<RowInBlock>>& temp_row_in_blocks) {
628
    // For flexible partial update, when table has sequence column, we don't do any aggregation
629
    // in memtable. These duplicate rows will be aggregated in VerticalSegmentWriter
630
0
    int row_pos = -1;
631
0
    for (const auto& row_ptr : *_row_in_blocks) {
632
0
        RowInBlock* row = row_ptr.get();
633
0
        temp_row_in_blocks.push_back(row_ptr);
634
0
        _finalize_one_row<is_final>(row, mutable_block, ++row_pos);
635
0
    }
636
0
}
Unexecuted instantiation: _ZN5doris8MemTable51_aggregate_for_flexible_partial_update_with_seq_colILb0EEEvRNS_12MutableBlockERSt6vectorISt10shared_ptrINS_10RowInBlockEENS_18CustomStdAllocatorIS7_NS_9AllocatorILb0ELb0ELb0ENS_22DefaultMemoryAllocatorELb1EEEEEE
Unexecuted instantiation: _ZN5doris8MemTable51_aggregate_for_flexible_partial_update_with_seq_colILb1EEEvRNS_12MutableBlockERSt6vectorISt10shared_ptrINS_10RowInBlockEENS_18CustomStdAllocatorIS7_NS_9AllocatorILb0ELb0ELb0ENS_22DefaultMemoryAllocatorELb1EEEEEE
637
638
0
void MemTable::shrink_memtable_by_agg() {
639
0
    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(
640
0
            _resource_ctx->memory_context()->mem_tracker()->write_tracker());
641
0
    SCOPED_CONSUME_MEM_TRACKER(_mem_tracker);
642
0
    if (_keys_type == KeysType::DUP_KEYS) {
643
0
        return;
644
0
    }
645
0
    size_t same_keys_num = _sort();
646
0
    if (same_keys_num != 0) {
647
0
        (_skip_bitmap_col_idx == -1) ? _aggregate<false, false>() : _aggregate<false, true>();
648
0
    }
649
0
    _last_agg_pos = memory_usage();
650
0
}
651
652
42
bool MemTable::need_flush() const {
653
42
    DBUG_EXECUTE_IF("MemTable.need_flush", { return true; });
654
42
    auto max_size = _adaptive_write_buffer_size();
655
42
    if (_partial_update_mode == UniqueKeyUpdateModePB::UPDATE_FIXED_COLUMNS) {
656
0
        auto update_columns_size = _num_columns;
657
0
        auto min_buffer_size = config::min_write_buffer_size_for_partial_update;
658
0
        max_size = max_size * update_columns_size / _tablet_schema->num_columns();
659
0
        max_size = max_size > min_buffer_size ? max_size : min_buffer_size;
660
0
    }
661
662
42
    if (memory_usage() >= max_size) {
663
0
        g_flush_cuz_memtable_full << 1;
664
0
        return true;
665
0
    }
666
42
    return false;
667
42
}
668
669
42
int64_t MemTable::_adaptive_write_buffer_size() const {
670
42
    if (!config::enable_adaptive_write_buffer_size) [[unlikely]] {
671
0
        return config::write_buffer_size;
672
0
    }
673
42
    auto* memtable_limiter = ExecEnv::GetInstance()->memtable_memory_limiter();
674
42
    int64_t memtable_mem =
675
42
            (memtable_limiter != nullptr && memtable_limiter->mem_tracker() != nullptr)
676
42
                    ? memtable_limiter->mem_tracker()->consumption()
677
42
                    : 0;
678
42
    int64_t factor = 4;
679
    // Memory usage intervals:
680
    // (80 %, 100 %] → 1× buffer
681
    // (50 %, 80 %]  → 2× buffer
682
    // [0 %, 50 %]   → 4× buffer
683
42
    if (memtable_mem > (_load_mem_limit * 4) / 5) { // > 80 %
684
0
        factor = 1;
685
42
    } else if (memtable_mem > _load_mem_limit / 2) { // > 50 %
686
0
        factor = 2;
687
0
    }
688
42
    return config::write_buffer_size * factor;
689
42
}
690
691
42
bool MemTable::need_agg() const {
692
42
    if (_keys_type == KeysType::AGG_KEYS) {
693
10
        auto max_size = _last_agg_pos + config::write_buffer_size_for_agg;
694
10
        return memory_usage() >= max_size;
695
10
    }
696
32
    return false;
697
42
}
698
699
0
size_t MemTable::get_flush_reserve_memory_size() const {
700
0
    if (_keys_type == KeysType::DUP_KEYS && _tablet_schema->num_key_columns() == 0) {
701
0
        return 0; // no need to reserve
702
0
    }
703
0
    return static_cast<size_t>(static_cast<double>(_input_mutable_block.allocated_bytes()) * 1.2);
704
0
}
705
706
24
Status MemTable::_to_block(std::unique_ptr<Block>* res) {
707
24
    size_t same_keys_num = _sort();
708
24
    if (_keys_type == KeysType::DUP_KEYS || same_keys_num == 0) {
709
18
        if (_keys_type == KeysType::DUP_KEYS && _tablet_schema->num_key_columns() == 0) {
710
0
            _output_mutable_block.swap(_input_mutable_block);
711
18
        } else {
712
18
            Block in_block = _input_mutable_block.to_block();
713
18
            RETURN_IF_ERROR(_put_into_output(in_block));
714
18
        }
715
18
    } else {
716
6
        (_skip_bitmap_col_idx == -1) ? _aggregate<true, false>() : _aggregate<true, true>();
717
6
    }
718
24
    if (_keys_type == KeysType::UNIQUE_KEYS && _enable_unique_key_mow &&
719
24
        !_tablet_schema->cluster_key_uids().empty()) {
720
2
        if (_partial_update_mode != UniqueKeyUpdateModePB::UPSERT) {
721
0
            return Status::InternalError(
722
0
                    "Partial update for mow with cluster keys is not supported");
723
0
        }
724
2
        RETURN_IF_ERROR(_sort_by_cluster_keys());
725
2
    }
726
24
    _input_mutable_block.clear();
727
24
    *res = Block::create_unique(_output_mutable_block.to_block());
728
24
    return Status::OK();
729
24
}
730
731
24
Status MemTable::to_block(std::unique_ptr<Block>* res) {
732
24
    RETURN_IF_ERROR_OR_CATCH_EXCEPTION(_to_block(res));
733
24
    return Status::OK();
734
24
}
735
736
#include "common/compile_check_end.h"
737
} // namespace doris