Coverage Report

Created: 2026-08-14 19:23

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