Coverage Report

Created: 2026-07-03 18:15

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