Coverage Report

Created: 2026-07-08 03:15

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