Coverage Report

Created: 2025-11-21 12:46

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