Coverage Report

Created: 2026-07-15 10:06

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