Coverage Report

Created: 2026-03-15 15:59

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