Coverage Report

Created: 2026-08-04 11:20

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