Coverage Report

Created: 2025-12-30 13:11

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