Coverage Report

Created: 2026-05-11 23:41

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