Coverage Report

Created: 2025-10-16 13:21

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