Coverage Report

Created: 2025-07-23 16:44

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