Coverage Report

Created: 2025-05-13 09:18

/root/doris/be/src/olap/memtable.cpp
Line
Count
Source (jump to first uncovered line)
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
        : _mem_type(MemType::ACTIVE),
56
          _tablet_id(tablet_id),
57
          _enable_unique_key_mow(enable_unique_key_mow),
58
          _keys_type(tablet_schema->keys_type()),
59
          _tablet_schema(tablet_schema),
60
          _resource_ctx(resource_ctx),
61
          _is_first_insertion(true),
62
          _agg_functions(tablet_schema->num_columns()),
63
          _offsets_of_aggregate_states(tablet_schema->num_columns()),
64
83.8k
          _total_size_of_aggregate_states(0) {
65
83.8k
    g_memtable_cnt << 1;
66
83.8k
    _mem_tracker = std::make_shared<MemTracker>();
67
83.8k
    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(
68
83.8k
            _resource_ctx->memory_context()->mem_tracker()->write_tracker());
69
83.8k
    SCOPED_CONSUME_MEM_TRACKER(_mem_tracker);
70
83.8k
    _arena = std::make_unique<vectorized::Arena>();
71
83.8k
    _vec_row_comparator = std::make_shared<RowInBlockComparator>(_tablet_schema);
72
83.8k
    _num_columns = _tablet_schema->num_columns();
73
83.8k
    if (partial_update_info != nullptr) {
74
83.8k
        _partial_update_mode = partial_update_info->update_mode();
75
83.8k
        if (_partial_update_mode == UniqueKeyUpdateModePB::UPDATE_FIXED_COLUMNS) {
76
2.45k
            _num_columns = partial_update_info->partial_update_input_columns.size();
77
2.45k
            if (partial_update_info->is_schema_contains_auto_inc_column &&
78
2.45k
                !partial_update_info->is_input_columns_contains_auto_inc_column) {
79
193
                _is_partial_update_and_auto_inc = true;
80
193
                _num_columns += 1;
81
193
            }
82
2.45k
        }
83
83.8k
    }
84
    // TODO: Support ZOrderComparator in the future
85
83.8k
    _init_columns_offset_by_slot_descs(slot_descs, tuple_desc);
86
83.8k
    _row_in_blocks = std::make_unique<DorisVector<RowInBlock*>>();
87
83.8k
}
88
89
void MemTable::_init_columns_offset_by_slot_descs(const std::vector<SlotDescriptor*>* slot_descs,
90
83.8k
                                                  const TupleDescriptor* tuple_desc) {
91
1.16M
    for (auto slot_desc : *slot_descs) {
92
1.16M
        const auto& slots = tuple_desc->slots();
93
17.2M
        for (int j = 0; j < slots.size(); ++j) {
94
17.2M
            if (slot_desc->id() == slots[j]->id()) {
95
1.16M
                _column_offset.emplace_back(j);
96
1.16M
                break;
97
1.16M
            }
98
17.2M
        }
99
1.16M
    }
100
83.8k
    if (_is_partial_update_and_auto_inc) {
101
193
        _column_offset.emplace_back(_column_offset.size());
102
193
    }
103
83.8k
}
104
105
29.3k
void MemTable::_init_agg_functions(const vectorized::Block* block) {
106
351k
    for (auto cid = _tablet_schema->num_key_columns(); cid < _num_columns; ++cid) {
107
322k
        vectorized::AggregateFunctionPtr function;
108
322k
        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
272k
            if (_skip_bitmap_col_idx != cid) {
112
271k
                function = vectorized::AggregateFunctionSimpleFactory::instance().get(
113
271k
                        "replace_load", {block->get_data_type(cid)},
114
271k
                        block->get_data_type(cid)->is_nullable(),
115
271k
                        BeExecVersionManager::get_newest_version());
116
271k
            } else {
117
278
                function = vectorized::AggregateFunctionSimpleFactory::instance().get(
118
278
                        "bitmap_intersect", {block->get_data_type(cid)}, false,
119
278
                        BeExecVersionManager::get_newest_version());
120
278
            }
121
272k
        } else {
122
49.9k
            function = _tablet_schema->column(cid).get_aggregate_function(
123
49.9k
                    vectorized::AGG_LOAD_SUFFIX, _tablet_schema->column(cid).get_be_exec_version());
124
49.9k
            if (function == nullptr) {
125
0
                LOG(WARNING) << "column get aggregate function failed, column="
126
0
                             << _tablet_schema->column(cid).name();
127
0
            }
128
49.9k
        }
129
130
322k
        DCHECK(function != nullptr);
131
322k
        _agg_functions[cid] = function;
132
322k
    }
133
134
351k
    for (auto cid = _tablet_schema->num_key_columns(); cid < _num_columns; ++cid) {
135
322k
        _offsets_of_aggregate_states[cid] = _total_size_of_aggregate_states;
136
322k
        _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
322k
        if (cid + 1 < _num_columns) {
140
292k
            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
292k
            _total_size_of_aggregate_states =
145
292k
                    (_total_size_of_aggregate_states + alignment_of_next_state - 1) /
146
292k
                    alignment_of_next_state * alignment_of_next_state;
147
292k
        }
148
322k
    }
149
29.3k
}
150
151
83.8k
MemTable::~MemTable() {
152
83.8k
    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(
153
83.8k
            _resource_ctx->memory_context()->mem_tracker()->write_tracker());
154
83.8k
    {
155
83.8k
        SCOPED_CONSUME_MEM_TRACKER(_mem_tracker);
156
83.8k
        g_memtable_cnt << -1;
157
83.8k
        if (_keys_type != KeysType::DUP_KEYS) {
158
14.1M
            for (auto it = _row_in_blocks->begin(); it != _row_in_blocks->end(); it++) {
159
14.1M
                if (!(*it)->has_init_agg()) {
160
14.1M
                    continue;
161
14.1M
                }
162
                // We should release agg_places here, because they are not released when a
163
                // load is canceled.
164
18.4E
                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
18.4E
            }
170
42.3k
        }
171
172
83.8k
        std::for_each(_row_in_blocks->begin(), _row_in_blocks->end(),
173
83.8k
                      std::default_delete<RowInBlock>());
174
        // Arena has to be destroyed after agg state, because some agg state's memory may be
175
        // allocated in arena.
176
83.8k
        _arena.reset();
177
83.8k
        _vec_row_comparator.reset();
178
83.8k
        _row_in_blocks.reset();
179
83.8k
        _agg_functions.clear();
180
83.8k
        _input_mutable_block.clear();
181
83.8k
        _output_mutable_block.clear();
182
83.8k
    }
183
83.8k
    if (_is_flush_success) {
184
        // If the memtable is flush success, then its memtracker's consumption should be 0
185
63.4k
        if (_mem_tracker->consumption() != 0 && config::crash_in_memory_tracker_inaccurate) {
186
0
            LOG(FATAL) << "memtable flush success but cosumption is not 0, it is "
187
0
                       << _mem_tracker->consumption();
188
0
        }
189
63.4k
    }
190
83.8k
}
191
192
418k
int RowInBlockComparator::operator()(const RowInBlock* left, const RowInBlock* right) const {
193
418k
    return _pblock->compare_at(left->_row_pos, right->_row_pos, _tablet_schema->num_key_columns(),
194
418k
                               *_pblock, -1);
195
418k
}
196
197
Status MemTable::insert(const vectorized::Block* input_block,
198
134k
                        const DorisVector<uint32_t>& row_idxs) {
199
134k
    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(
200
134k
            _resource_ctx->memory_context()->mem_tracker()->write_tracker());
201
134k
    SCOPED_CONSUME_MEM_TRACKER(_mem_tracker);
202
203
134k
    if (_is_first_insertion) {
204
63.4k
        _is_first_insertion = false;
205
63.4k
        auto clone_block = input_block->clone_without_columns(&_column_offset);
206
63.4k
        _input_mutable_block = vectorized::MutableBlock::build_mutable_block(&clone_block);
207
63.4k
        _vec_row_comparator->set_block(&_input_mutable_block);
208
63.4k
        _output_mutable_block = vectorized::MutableBlock::build_mutable_block(&clone_block);
209
63.4k
        if (_tablet_schema->has_sequence_col()) {
210
1.18k
            if (_partial_update_mode == UniqueKeyUpdateModePB::UPDATE_FIXED_COLUMNS) {
211
                // for unique key fixed partial update, sequence column index in block
212
                // may be different with the index in `_tablet_schema`
213
510
                for (int32_t i = 0; i < clone_block.columns(); i++) {
214
411
                    if (clone_block.get_by_position(i).name == SEQUENCE_COL) {
215
38
                        _seq_col_idx_in_block = i;
216
38
                        break;
217
38
                    }
218
411
                }
219
1.04k
            } else {
220
1.04k
                _seq_col_idx_in_block = _tablet_schema->sequence_col_idx();
221
1.04k
            }
222
1.18k
        }
223
63.4k
        if (_partial_update_mode == UniqueKeyUpdateModePB::UPDATE_FLEXIBLE_COLUMNS &&
224
63.4k
            _tablet_schema->has_skip_bitmap_col()) {
225
            // init of _skip_bitmap_col_idx must be before _init_agg_functions()
226
278
            _skip_bitmap_col_idx = _tablet_schema->skip_bitmap_col_idx();
227
278
            if (_seq_col_idx_in_block != -1) {
228
24
                _seq_col_unique_id = _tablet_schema->column(_seq_col_idx_in_block).unique_id();
229
24
            }
230
278
        }
231
63.4k
        if (_keys_type != KeysType::DUP_KEYS) {
232
            // there may be additional intermediate columns in input_block
233
            // we only need columns indicated by column offset in the output
234
29.3k
            RETURN_IF_CATCH_EXCEPTION(_init_agg_functions(&clone_block));
235
29.3k
        }
236
63.4k
    }
237
238
134k
    auto num_rows = row_idxs.size();
239
134k
    size_t cursor_in_mutableblock = _input_mutable_block.rows();
240
134k
    RETURN_IF_ERROR(_input_mutable_block.add_rows(input_block, row_idxs.data(),
241
134k
                                                  row_idxs.data() + num_rows, &_column_offset));
242
37.5M
    for (int i = 0; i < num_rows; i++) {
243
37.3M
        _row_in_blocks->emplace_back(new RowInBlock {cursor_in_mutableblock + i});
244
37.3M
    }
245
246
134k
    _stat.raw_rows += num_rows;
247
134k
    return Status::OK();
248
134k
}
249
250
template <bool has_skip_bitmap_col>
251
void MemTable::_aggregate_two_row_in_block(vectorized::MutableBlock& mutable_block,
252
99.0k
                                           RowInBlock* src_row, RowInBlock* dst_row) {
253
    // for flexible partial update, the caller must guarantees that either src_row and dst_row
254
    // both specify the sequence column, or src_row and dst_row both don't specify the
255
    // sequence column
256
99.0k
    if (_tablet_schema->has_sequence_col() && _seq_col_idx_in_block >= 0) {
257
326
        DCHECK_LT(_seq_col_idx_in_block, mutable_block.columns());
258
326
        auto col_ptr = mutable_block.mutable_columns()[_seq_col_idx_in_block].get();
259
326
        auto res = col_ptr->compare_at(dst_row->_row_pos, src_row->_row_pos, *col_ptr, -1);
260
        // dst sequence column larger than src, don't need to update
261
326
        if (res > 0) {
262
106
            return;
263
106
        }
264
        // need to update the row pos in dst row to the src row pos when has
265
        // sequence column
266
220
        dst_row->_row_pos = src_row->_row_pos;
267
220
    }
268
    // dst is non-sequence row, or dst sequence is smaller
269
98.9k
    if constexpr (!has_skip_bitmap_col) {
270
4.08k
        DCHECK(_skip_bitmap_col_idx == -1);
271
402k
        for (size_t cid = _tablet_schema->num_key_columns(); cid < _num_columns; ++cid) {
272
307k
            auto* col_ptr = mutable_block.mutable_columns()[cid].get();
273
307k
            _agg_functions[cid]->add(dst_row->agg_places(cid),
274
307k
                                     const_cast<const doris::vectorized::IColumn**>(&col_ptr),
275
307k
                                     src_row->_row_pos, _arena.get());
276
307k
        }
277
94.6k
    } else {
278
4.08k
        DCHECK(_skip_bitmap_col_idx != -1);
279
4.08k
        DCHECK_LT(_skip_bitmap_col_idx, mutable_block.columns());
280
4.08k
        const BitmapValue& skip_bitmap =
281
4.08k
                assert_cast<vectorized::ColumnBitmap*, TypeCheckOnRelease::DISABLE>(
282
4.08k
                        mutable_block.mutable_columns()[_skip_bitmap_col_idx].get())
283
4.08k
                        ->get_data()[src_row->_row_pos];
284
73.7k
        for (size_t cid = _tablet_schema->num_key_columns(); cid < _num_columns; ++cid) {
285
69.6k
            const auto& col = _tablet_schema->column(cid);
286
69.6k
            if (cid != _skip_bitmap_col_idx && skip_bitmap.contains(col.unique_id())) {
287
34.8k
                continue;
288
34.8k
            }
289
34.7k
            auto* col_ptr = mutable_block.mutable_columns()[cid].get();
290
34.7k
            _agg_functions[cid]->add(dst_row->agg_places(cid),
291
34.7k
                                     const_cast<const doris::vectorized::IColumn**>(&col_ptr),
292
34.7k
                                     src_row->_row_pos, _arena.get());
293
34.7k
        }
294
4.08k
    }
295
98.9k
}
_ZN5doris8MemTable27_aggregate_two_row_in_blockILb0EEEvRNS_10vectorized12MutableBlockEPNS_10RowInBlockES6_
Line
Count
Source
252
94.9k
                                           RowInBlock* src_row, RowInBlock* dst_row) {
253
    // for flexible partial update, the caller must guarantees that either src_row and dst_row
254
    // both specify the sequence column, or src_row and dst_row both don't specify the
255
    // sequence column
256
94.9k
    if (_tablet_schema->has_sequence_col() && _seq_col_idx_in_block >= 0) {
257
170
        DCHECK_LT(_seq_col_idx_in_block, mutable_block.columns());
258
170
        auto col_ptr = mutable_block.mutable_columns()[_seq_col_idx_in_block].get();
259
170
        auto res = col_ptr->compare_at(dst_row->_row_pos, src_row->_row_pos, *col_ptr, -1);
260
        // dst sequence column larger than src, don't need to update
261
170
        if (res > 0) {
262
88
            return;
263
88
        }
264
        // need to update the row pos in dst row to the src row pos when has
265
        // sequence column
266
82
        dst_row->_row_pos = src_row->_row_pos;
267
82
    }
268
    // dst is non-sequence row, or dst sequence is smaller
269
94.8k
    if constexpr (!has_skip_bitmap_col) {
270
94.6k
        DCHECK(_skip_bitmap_col_idx == -1);
271
402k
        for (size_t cid = _tablet_schema->num_key_columns(); cid < _num_columns; ++cid) {
272
307k
            auto* col_ptr = mutable_block.mutable_columns()[cid].get();
273
307k
            _agg_functions[cid]->add(dst_row->agg_places(cid),
274
307k
                                     const_cast<const doris::vectorized::IColumn**>(&col_ptr),
275
307k
                                     src_row->_row_pos, _arena.get());
276
307k
        }
277
94.6k
    } else {
278
94.8k
        DCHECK(_skip_bitmap_col_idx != -1);
279
94.8k
        DCHECK_LT(_skip_bitmap_col_idx, mutable_block.columns());
280
94.8k
        const BitmapValue& skip_bitmap =
281
94.8k
                assert_cast<vectorized::ColumnBitmap*, TypeCheckOnRelease::DISABLE>(
282
94.8k
                        mutable_block.mutable_columns()[_skip_bitmap_col_idx].get())
283
94.8k
                        ->get_data()[src_row->_row_pos];
284
94.8k
        for (size_t cid = _tablet_schema->num_key_columns(); cid < _num_columns; ++cid) {
285
94.8k
            const auto& col = _tablet_schema->column(cid);
286
94.8k
            if (cid != _skip_bitmap_col_idx && skip_bitmap.contains(col.unique_id())) {
287
94.8k
                continue;
288
94.8k
            }
289
94.8k
            auto* col_ptr = mutable_block.mutable_columns()[cid].get();
290
94.8k
            _agg_functions[cid]->add(dst_row->agg_places(cid),
291
94.8k
                                     const_cast<const doris::vectorized::IColumn**>(&col_ptr),
292
94.8k
                                     src_row->_row_pos, _arena.get());
293
94.8k
        }
294
94.8k
    }
295
94.8k
}
_ZN5doris8MemTable27_aggregate_two_row_in_blockILb1EEEvRNS_10vectorized12MutableBlockEPNS_10RowInBlockES6_
Line
Count
Source
252
4.09k
                                           RowInBlock* src_row, RowInBlock* dst_row) {
253
    // for flexible partial update, the caller must guarantees that either src_row and dst_row
254
    // both specify the sequence column, or src_row and dst_row both don't specify the
255
    // sequence column
256
4.09k
    if (_tablet_schema->has_sequence_col() && _seq_col_idx_in_block >= 0) {
257
156
        DCHECK_LT(_seq_col_idx_in_block, mutable_block.columns());
258
156
        auto col_ptr = mutable_block.mutable_columns()[_seq_col_idx_in_block].get();
259
156
        auto res = col_ptr->compare_at(dst_row->_row_pos, src_row->_row_pos, *col_ptr, -1);
260
        // dst sequence column larger than src, don't need to update
261
156
        if (res > 0) {
262
18
            return;
263
18
        }
264
        // need to update the row pos in dst row to the src row pos when has
265
        // sequence column
266
138
        dst_row->_row_pos = src_row->_row_pos;
267
138
    }
268
    // dst is non-sequence row, or dst sequence is smaller
269
4.08k
    if constexpr (!has_skip_bitmap_col) {
270
4.08k
        DCHECK(_skip_bitmap_col_idx == -1);
271
4.08k
        for (size_t cid = _tablet_schema->num_key_columns(); cid < _num_columns; ++cid) {
272
4.08k
            auto* col_ptr = mutable_block.mutable_columns()[cid].get();
273
4.08k
            _agg_functions[cid]->add(dst_row->agg_places(cid),
274
4.08k
                                     const_cast<const doris::vectorized::IColumn**>(&col_ptr),
275
4.08k
                                     src_row->_row_pos, _arena.get());
276
4.08k
        }
277
4.08k
    } else {
278
4.08k
        DCHECK(_skip_bitmap_col_idx != -1);
279
4.08k
        DCHECK_LT(_skip_bitmap_col_idx, mutable_block.columns());
280
4.08k
        const BitmapValue& skip_bitmap =
281
4.08k
                assert_cast<vectorized::ColumnBitmap*, TypeCheckOnRelease::DISABLE>(
282
4.08k
                        mutable_block.mutable_columns()[_skip_bitmap_col_idx].get())
283
4.08k
                        ->get_data()[src_row->_row_pos];
284
73.7k
        for (size_t cid = _tablet_schema->num_key_columns(); cid < _num_columns; ++cid) {
285
69.6k
            const auto& col = _tablet_schema->column(cid);
286
69.6k
            if (cid != _skip_bitmap_col_idx && skip_bitmap.contains(col.unique_id())) {
287
34.8k
                continue;
288
34.8k
            }
289
34.7k
            auto* col_ptr = mutable_block.mutable_columns()[cid].get();
290
34.7k
            _agg_functions[cid]->add(dst_row->agg_places(cid),
291
34.7k
                                     const_cast<const doris::vectorized::IColumn**>(&col_ptr),
292
34.7k
                                     src_row->_row_pos, _arena.get());
293
34.7k
        }
294
4.08k
    }
295
4.08k
}
296
61.2k
Status MemTable::_put_into_output(vectorized::Block& in_block) {
297
61.2k
    SCOPED_RAW_TIMER(&_stat.put_into_output_ns);
298
61.2k
    DorisVector<uint32_t> row_pos_vec;
299
61.2k
    DCHECK(in_block.rows() <= std::numeric_limits<int>::max());
300
61.2k
    row_pos_vec.reserve(in_block.rows());
301
36.4M
    for (int i = 0; i < _row_in_blocks->size(); i++) {
302
36.4M
        row_pos_vec.emplace_back((*_row_in_blocks)[i]->_row_pos);
303
36.4M
    }
304
61.2k
    return _output_mutable_block.add_rows(&in_block, row_pos_vec.data(),
305
61.2k
                                          row_pos_vec.data() + in_block.rows());
306
61.2k
}
307
308
63.4k
size_t MemTable::_sort() {
309
63.4k
    SCOPED_RAW_TIMER(&_stat.sort_ns);
310
63.4k
    _stat.sort_times++;
311
63.4k
    size_t same_keys_num = 0;
312
    // sort new rows
313
63.4k
    Tie tie = Tie(_last_sorted_pos, _row_in_blocks->size());
314
249k
    for (size_t i = 0; i < _tablet_schema->num_key_columns(); i++) {
315
378M
        auto cmp = [&](const RowInBlock* lhs, const RowInBlock* rhs) -> int {
316
378M
            return _input_mutable_block.compare_one_column(lhs->_row_pos, rhs->_row_pos, i, -1);
317
378M
        };
318
185k
        _sort_one_column(*_row_in_blocks, tie, cmp);
319
185k
    }
320
63.4k
    bool is_dup = (_keys_type == KeysType::DUP_KEYS);
321
    // sort extra round by _row_pos to make the sort stable
322
63.4k
    auto iter = tie.iter();
323
253k
    while (iter.next()) {
324
190k
        pdqsort(std::next(_row_in_blocks->begin(), iter.left()),
325
190k
                std::next(_row_in_blocks->begin(), iter.right()),
326
18.6M
                [&is_dup](const RowInBlock* lhs, const RowInBlock* rhs) -> bool {
327
18.6M
                    return is_dup ? lhs->_row_pos > rhs->_row_pos : lhs->_row_pos < rhs->_row_pos;
328
18.6M
                });
329
190k
        same_keys_num += iter.right() - iter.left();
330
190k
    }
331
    // merge new rows and old rows
332
63.4k
    _vec_row_comparator->set_block(&_input_mutable_block);
333
63.4k
    auto cmp_func = [this, is_dup, &same_keys_num](const RowInBlock* l,
334
63.4k
                                                   const RowInBlock* r) -> bool {
335
0
        auto value = (*(this->_vec_row_comparator))(l, r);
336
0
        if (value == 0) {
337
0
            same_keys_num++;
338
0
            return is_dup ? l->_row_pos > r->_row_pos : l->_row_pos < r->_row_pos;
339
0
        } else {
340
0
            return value < 0;
341
0
        }
342
0
    };
343
63.4k
    auto new_row_it = std::next(_row_in_blocks->begin(), _last_sorted_pos);
344
63.4k
    std::inplace_merge(_row_in_blocks->begin(), new_row_it, _row_in_blocks->end(), cmp_func);
345
63.4k
    _last_sorted_pos = _row_in_blocks->size();
346
63.4k
    return same_keys_num;
347
63.4k
}
348
349
1.55k
Status MemTable::_sort_by_cluster_keys() {
350
1.55k
    SCOPED_RAW_TIMER(&_stat.sort_ns);
351
1.55k
    _stat.sort_times++;
352
    // sort all rows
353
1.55k
    vectorized::Block in_block = _output_mutable_block.to_block();
354
1.55k
    vectorized::MutableBlock mutable_block =
355
1.55k
            vectorized::MutableBlock::build_mutable_block(&in_block);
356
1.55k
    auto clone_block = in_block.clone_without_columns();
357
1.55k
    _output_mutable_block = vectorized::MutableBlock::build_mutable_block(&clone_block);
358
359
1.55k
    DorisVector<RowInBlock*> row_in_blocks;
360
1.55k
    std::unique_ptr<int, std::function<void(int*)>> row_in_blocks_deleter((int*)0x01, [&](int*) {
361
1.55k
        std::for_each(row_in_blocks.begin(), row_in_blocks.end(),
362
1.55k
                      std::default_delete<RowInBlock>());
363
1.55k
    });
364
1.55k
    row_in_blocks.reserve(mutable_block.rows());
365
809k
    for (size_t i = 0; i < mutable_block.rows(); i++) {
366
808k
        row_in_blocks.emplace_back(new RowInBlock {i});
367
808k
    }
368
1.55k
    Tie tie = Tie(0, mutable_block.rows());
369
370
3.77k
    for (auto cid : _tablet_schema->cluster_key_uids()) {
371
3.77k
        auto index = _tablet_schema->field_index(cid);
372
3.77k
        if (index == -1) {
373
0
            return Status::InternalError("could not find cluster key column with unique_id=" +
374
0
                                         std::to_string(cid) + " in tablet schema");
375
0
        }
376
8.48M
        auto cmp = [&](const RowInBlock* lhs, const RowInBlock* rhs) -> int {
377
8.48M
            return mutable_block.compare_one_column(lhs->_row_pos, rhs->_row_pos, index, -1);
378
8.48M
        };
379
3.77k
        _sort_one_column(row_in_blocks, tie, cmp);
380
3.77k
    }
381
382
    // sort extra round by _row_pos to make the sort stable
383
1.55k
    auto iter = tie.iter();
384
119k
    while (iter.next()) {
385
117k
        pdqsort(std::next(row_in_blocks.begin(), iter.left()),
386
117k
                std::next(row_in_blocks.begin(), iter.right()),
387
847k
                [](const RowInBlock* lhs, const RowInBlock* rhs) -> bool {
388
847k
                    return lhs->_row_pos < rhs->_row_pos;
389
847k
                });
390
117k
    }
391
392
1.55k
    in_block = mutable_block.to_block();
393
1.55k
    SCOPED_RAW_TIMER(&_stat.put_into_output_ns);
394
1.55k
    DorisVector<uint32_t> row_pos_vec;
395
1.55k
    DCHECK(in_block.rows() <= std::numeric_limits<int>::max());
396
1.55k
    row_pos_vec.reserve(in_block.rows());
397
820k
    for (int i = 0; i < row_in_blocks.size(); i++) {
398
818k
        row_pos_vec.emplace_back(row_in_blocks[i]->_row_pos);
399
818k
    }
400
1.55k
    std::vector<int> column_offset;
401
21.5k
    for (int i = 0; i < _column_offset.size(); ++i) {
402
19.9k
        column_offset.emplace_back(i);
403
19.9k
    }
404
1.55k
    return _output_mutable_block.add_rows(&in_block, row_pos_vec.data(),
405
1.55k
                                          row_pos_vec.data() + in_block.rows(), &column_offset);
406
1.55k
}
407
408
void MemTable::_sort_one_column(DorisVector<RowInBlock*>& row_in_blocks, Tie& tie,
409
189k
                                std::function<int(const RowInBlock*, const RowInBlock*)> cmp) {
410
189k
    auto iter = tie.iter();
411
6.17M
    while (iter.next()) {
412
5.98M
        pdqsort(std::next(row_in_blocks.begin(), static_cast<int>(iter.left())),
413
5.98M
                std::next(row_in_blocks.begin(), static_cast<int>(iter.right())),
414
308M
                [&cmp](auto lhs, auto rhs) -> bool { return cmp(lhs, rhs) < 0; });
415
5.98M
        tie[iter.left()] = 0;
416
64.5M
        for (auto i = iter.left() + 1; i < iter.right(); i++) {
417
58.5M
            tie[i] = (cmp(row_in_blocks[i - 1], row_in_blocks[i]) == 0);
418
58.5M
        }
419
5.98M
    }
420
189k
}
421
422
template <bool is_final>
423
void MemTable::_finalize_one_row(RowInBlock* row,
424
                                 const vectorized::ColumnsWithTypeAndName& block_data,
425
321k
                                 int row_pos) {
426
    // move key columns
427
846k
    for (size_t i = 0; i < _tablet_schema->num_key_columns(); ++i) {
428
524k
        _output_mutable_block.get_column_by_position(i)->insert_from(*block_data[i].column.get(),
429
524k
                                                                     row->_row_pos);
430
524k
    }
431
321k
    if (row->has_init_agg()) {
432
        // get value columns from agg_places
433
84.9k
        for (size_t i = _tablet_schema->num_key_columns(); i < _num_columns; ++i) {
434
76.6k
            auto function = _agg_functions[i];
435
76.6k
            auto* agg_place = row->agg_places(i);
436
76.6k
            auto* col_ptr = _output_mutable_block.get_column_by_position(i).get();
437
76.6k
            function->insert_result_into(agg_place, *col_ptr);
438
439
76.6k
            if constexpr (is_final) {
440
0
                function->destroy(agg_place);
441
0
            } else {
442
0
                function->reset(agg_place);
443
0
            }
444
76.6k
        }
445
446
8.31k
        if constexpr (is_final) {
447
0
            row->remove_init_agg();
448
0
        } else {
449
0
            for (size_t i = _tablet_schema->num_key_columns(); i < _num_columns; ++i) {
450
0
                auto function = _agg_functions[i];
451
0
                auto* agg_place = row->agg_places(i);
452
0
                auto* col_ptr = _output_mutable_block.get_column_by_position(i).get();
453
0
                function->add(agg_place, const_cast<const doris::vectorized::IColumn**>(&col_ptr),
454
0
                              row_pos, _arena.get());
455
0
            }
456
0
        }
457
313k
    } else {
458
        // move columns for rows do not need agg
459
5.74M
        for (size_t i = _tablet_schema->num_key_columns(); i < _num_columns; ++i) {
460
5.43M
            _output_mutable_block.get_column_by_position(i)->insert_from(
461
5.43M
                    *block_data[i].column.get(), row->_row_pos);
462
5.43M
        }
463
313k
    }
464
321k
    if constexpr (!is_final) {
465
0
        row->_row_pos = row_pos;
466
0
    }
467
321k
}
Unexecuted instantiation: _ZN5doris8MemTable17_finalize_one_rowILb0EEEvPNS_10RowInBlockERKSt6vectorINS_10vectorized21ColumnWithTypeAndNameESaIS6_EEi
_ZN5doris8MemTable17_finalize_one_rowILb1EEEvPNS_10RowInBlockERKSt6vectorINS_10vectorized21ColumnWithTypeAndNameESaIS6_EEi
Line
Count
Source
425
321k
                                 int row_pos) {
426
    // move key columns
427
846k
    for (size_t i = 0; i < _tablet_schema->num_key_columns(); ++i) {
428
524k
        _output_mutable_block.get_column_by_position(i)->insert_from(*block_data[i].column.get(),
429
524k
                                                                     row->_row_pos);
430
524k
    }
431
321k
    if (row->has_init_agg()) {
432
        // get value columns from agg_places
433
84.9k
        for (size_t i = _tablet_schema->num_key_columns(); i < _num_columns; ++i) {
434
76.6k
            auto function = _agg_functions[i];
435
76.6k
            auto* agg_place = row->agg_places(i);
436
76.6k
            auto* col_ptr = _output_mutable_block.get_column_by_position(i).get();
437
76.6k
            function->insert_result_into(agg_place, *col_ptr);
438
439
76.6k
            if constexpr (is_final) {
440
76.5k
                function->destroy(agg_place);
441
76.5k
            } else {
442
76.6k
                function->reset(agg_place);
443
76.6k
            }
444
76.6k
        }
445
446
8.32k
        if constexpr (is_final) {
447
8.32k
            row->remove_init_agg();
448
8.32k
        } else {
449
8.31k
            for (size_t i = _tablet_schema->num_key_columns(); i < _num_columns; ++i) {
450
8.31k
                auto function = _agg_functions[i];
451
8.31k
                auto* agg_place = row->agg_places(i);
452
8.31k
                auto* col_ptr = _output_mutable_block.get_column_by_position(i).get();
453
8.31k
                function->add(agg_place, const_cast<const doris::vectorized::IColumn**>(&col_ptr),
454
8.31k
                              row_pos, _arena.get());
455
8.31k
            }
456
8.31k
        }
457
313k
    } else {
458
        // move columns for rows do not need agg
459
5.74M
        for (size_t i = _tablet_schema->num_key_columns(); i < _num_columns; ++i) {
460
5.43M
            _output_mutable_block.get_column_by_position(i)->insert_from(
461
5.43M
                    *block_data[i].column.get(), row->_row_pos);
462
5.43M
        }
463
313k
    }
464
321k
    if constexpr (!is_final) {
465
321k
        row->_row_pos = row_pos;
466
321k
    }
467
321k
}
468
469
template <bool is_final, bool has_skip_bitmap_col>
470
2.08k
void MemTable::_aggregate() {
471
2.08k
    SCOPED_RAW_TIMER(&_stat.agg_ns);
472
2.08k
    _stat.agg_times++;
473
2.08k
    vectorized::Block in_block = _input_mutable_block.to_block();
474
2.08k
    vectorized::MutableBlock mutable_block =
475
2.08k
            vectorized::MutableBlock::build_mutable_block(&in_block);
476
2.08k
    _vec_row_comparator->set_block(&mutable_block);
477
2.08k
    auto& block_data = in_block.get_columns_with_type_and_name();
478
2.08k
    DorisVector<RowInBlock*> temp_row_in_blocks;
479
2.08k
    temp_row_in_blocks.reserve(_last_sorted_pos);
480
2.08k
    RowInBlock* prev_row = nullptr;
481
2.08k
    int row_pos = -1;
482
    //only init agg if needed
483
484
8.32k
    auto init_for_agg = [&](RowInBlock* row) {
485
8.32k
        row->init_agg_places(_arena->aligned_alloc(_total_size_of_aggregate_states, 16),
486
8.32k
                             _offsets_of_aggregate_states.data());
487
84.8k
        for (auto cid = _tablet_schema->num_key_columns(); cid < _num_columns; cid++) {
488
76.5k
            auto* col_ptr = mutable_block.mutable_columns()[cid].get();
489
76.5k
            auto* data = prev_row->agg_places(cid);
490
76.5k
            _agg_functions[cid]->create(data);
491
76.5k
            _agg_functions[cid]->add(data, const_cast<const doris::vectorized::IColumn**>(&col_ptr),
492
76.5k
                                     prev_row->_row_pos, _arena.get());
493
76.5k
        }
494
8.32k
    };
Unexecuted instantiation: _ZZN5doris8MemTable10_aggregateILb0ELb0EEEvvENKUlPNS_10RowInBlockEE_clES3_
Unexecuted instantiation: _ZZN5doris8MemTable10_aggregateILb0ELb1EEEvvENKUlPNS_10RowInBlockEE_clES3_
_ZZN5doris8MemTable10_aggregateILb1ELb0EEEvvENKUlPNS_10RowInBlockEE_clES3_
Line
Count
Source
484
6.81k
    auto init_for_agg = [&](RowInBlock* row) {
485
6.81k
        row->init_agg_places(_arena->aligned_alloc(_total_size_of_aggregate_states, 16),
486
6.81k
                             _offsets_of_aggregate_states.data());
487
57.8k
        for (auto cid = _tablet_schema->num_key_columns(); cid < _num_columns; cid++) {
488
51.0k
            auto* col_ptr = mutable_block.mutable_columns()[cid].get();
489
51.0k
            auto* data = prev_row->agg_places(cid);
490
51.0k
            _agg_functions[cid]->create(data);
491
51.0k
            _agg_functions[cid]->add(data, const_cast<const doris::vectorized::IColumn**>(&col_ptr),
492
51.0k
                                     prev_row->_row_pos, _arena.get());
493
51.0k
        }
494
6.81k
    };
_ZZN5doris8MemTable10_aggregateILb1ELb1EEEvvENKUlPNS_10RowInBlockEE_clES3_
Line
Count
Source
484
1.50k
    auto init_for_agg = [&](RowInBlock* row) {
485
1.50k
        row->init_agg_places(_arena->aligned_alloc(_total_size_of_aggregate_states, 16),
486
1.50k
                             _offsets_of_aggregate_states.data());
487
27.0k
        for (auto cid = _tablet_schema->num_key_columns(); cid < _num_columns; cid++) {
488
25.5k
            auto* col_ptr = mutable_block.mutable_columns()[cid].get();
489
25.5k
            auto* data = prev_row->agg_places(cid);
490
25.5k
            _agg_functions[cid]->create(data);
491
25.5k
            _agg_functions[cid]->add(data, const_cast<const doris::vectorized::IColumn**>(&col_ptr),
492
25.5k
                                     prev_row->_row_pos, _arena.get());
493
25.5k
        }
494
1.50k
    };
495
496
2.08k
    if (!has_skip_bitmap_col || _seq_col_idx_in_block == -1) {
497
420k
        for (RowInBlock* cur_row : *_row_in_blocks) {
498
420k
            if (!temp_row_in_blocks.empty() && (*_vec_row_comparator)(prev_row, cur_row) == 0) {
499
99.0k
                if (!prev_row->has_init_agg()) {
500
8.24k
                    init_for_agg(prev_row);
501
8.24k
                }
502
99.0k
                _stat.merged_rows++;
503
99.0k
                _aggregate_two_row_in_block<has_skip_bitmap_col>(mutable_block, cur_row, prev_row);
504
321k
            } else {
505
321k
                prev_row = cur_row;
506
321k
                if (!temp_row_in_blocks.empty()) {
507
                    // no more rows to merge for prev row, finalize it
508
319k
                    _finalize_one_row<is_final>(temp_row_in_blocks.back(), block_data, row_pos);
509
319k
                }
510
321k
                temp_row_in_blocks.push_back(prev_row);
511
321k
                row_pos++;
512
321k
            }
513
420k
        }
514
2.07k
        if (!temp_row_in_blocks.empty()) {
515
            // finalize the last low
516
2.07k
            _finalize_one_row<is_final>(temp_row_in_blocks.back(), block_data, row_pos);
517
2.07k
        }
518
2.07k
    } else {
519
        // For flexible partial update and the table has sequence column, considering the following situation:
520
        // there are multiple rows with the same keys in memtable, some of them specify the sequence column,
521
        // some of them don't. We can't do the de-duplication in memtable becasue we can only know the value
522
        // of the sequence column of the row which don't specify seqeuence column in SegmentWriter after we
523
        // probe the historical data. So at here we can only merge rows that have sequence column together and
524
        // merge rows without sequence column together, and finally, perform deduplication on them in SegmentWriter.
525
526
        // !!ATTENTION!!: there may be rows with the same keys after MemTable::_aggregate() in this situation.
527
15
        RowInBlock* row_with_seq_col = nullptr;
528
15
        int row_pos_with_seq = -1;
529
15
        RowInBlock* row_without_seq_col = nullptr;
530
15
        int row_pos_without_seq = -1;
531
532
80
        auto finalize_rows = [&]() {
533
80
            if (row_with_seq_col != nullptr) {
534
64
                _finalize_one_row<is_final>(row_with_seq_col, block_data, row_pos_with_seq);
535
64
                row_with_seq_col = nullptr;
536
64
            }
537
80
            if (row_without_seq_col != nullptr) {
538
64
                _finalize_one_row<is_final>(row_without_seq_col, block_data, row_pos_without_seq);
539
64
                row_without_seq_col = nullptr;
540
64
            }
541
80
        };
Unexecuted instantiation: _ZZN5doris8MemTable10_aggregateILb0ELb1EEEvvENKUlvE_clEv
_ZZN5doris8MemTable10_aggregateILb1ELb1EEEvvENKUlvE_clEv
Line
Count
Source
532
80
        auto finalize_rows = [&]() {
533
80
            if (row_with_seq_col != nullptr) {
534
64
                _finalize_one_row<is_final>(row_with_seq_col, block_data, row_pos_with_seq);
535
64
                row_with_seq_col = nullptr;
536
64
            }
537
80
            if (row_without_seq_col != nullptr) {
538
64
                _finalize_one_row<is_final>(row_without_seq_col, block_data, row_pos_without_seq);
539
64
                row_without_seq_col = nullptr;
540
64
            }
541
80
        };
542
128
        auto add_row = [&](RowInBlock* row, bool with_seq_col) {
543
128
            temp_row_in_blocks.push_back(row);
544
128
            row_pos++;
545
128
            if (with_seq_col) {
546
64
                row_with_seq_col = row;
547
64
                row_pos_with_seq = row_pos;
548
64
            } else {
549
64
                row_without_seq_col = row;
550
64
                row_pos_without_seq = row_pos;
551
64
            }
552
128
        };
Unexecuted instantiation: _ZZN5doris8MemTable10_aggregateILb0ELb1EEEvvENKUlPNS_10RowInBlockEbE_clES3_b
_ZZN5doris8MemTable10_aggregateILb1ELb1EEEvvENKUlPNS_10RowInBlockEbE_clES3_b
Line
Count
Source
542
128
        auto add_row = [&](RowInBlock* row, bool with_seq_col) {
543
128
            temp_row_in_blocks.push_back(row);
544
128
            row_pos++;
545
128
            if (with_seq_col) {
546
64
                row_with_seq_col = row;
547
64
                row_pos_with_seq = row_pos;
548
64
            } else {
549
64
                row_without_seq_col = row;
550
64
                row_pos_without_seq = row_pos;
551
64
            }
552
128
        };
553
15
        auto& skip_bitmaps = assert_cast<vectorized::ColumnBitmap*>(
554
15
                                     mutable_block.mutable_columns()[_skip_bitmap_col_idx].get())
555
15
                                     ->get_data();
556
284
        for (auto* cur_row : *_row_in_blocks) {
557
284
            const BitmapValue& skip_bitmap = skip_bitmaps[cur_row->_row_pos];
558
284
            bool with_seq_col = !skip_bitmap.contains(_seq_col_unique_id);
559
            // compare keys, the keys of row_with_seq_col and row_with_seq_col is the same,
560
            // choose any of them if it's valid
561
284
            prev_row = (row_with_seq_col == nullptr) ? row_without_seq_col : row_with_seq_col;
562
284
            if (prev_row != nullptr && (*_vec_row_comparator)(prev_row, cur_row) == 0) {
563
220
                prev_row = (with_seq_col ? row_with_seq_col : row_without_seq_col);
564
220
                if (prev_row == nullptr) {
565
64
                    add_row(cur_row, with_seq_col);
566
64
                    continue;
567
64
                }
568
156
                if (!prev_row->has_init_agg()) {
569
72
                    init_for_agg(prev_row);
570
72
                }
571
156
                _stat.merged_rows++;
572
156
                _aggregate_two_row_in_block<has_skip_bitmap_col>(mutable_block, cur_row, prev_row);
573
156
            } else {
574
                // no more rows to merge for prev rows, finalize them
575
64
                finalize_rows();
576
64
                add_row(cur_row, with_seq_col);
577
64
            }
578
284
        }
579
        // finalize the last lows
580
15
        finalize_rows();
581
15
    }
582
2.08k
    if constexpr (!is_final) {
583
        // if is not final, we collect the agg results to input_block and then continue to insert
584
0
        _input_mutable_block.swap(_output_mutable_block);
585
        //TODO(weixang):opt here.
586
0
        std::unique_ptr<vectorized::Block> empty_input_block = in_block.create_same_struct_block(0);
587
0
        _output_mutable_block =
588
0
                vectorized::MutableBlock::build_mutable_block(empty_input_block.get());
589
0
        _output_mutable_block.clear_column_data();
590
0
        *_row_in_blocks = temp_row_in_blocks;
591
0
        _last_sorted_pos = _row_in_blocks->size();
592
0
    }
593
2.08k
}
Unexecuted instantiation: _ZN5doris8MemTable10_aggregateILb0ELb0EEEvv
Unexecuted instantiation: _ZN5doris8MemTable10_aggregateILb0ELb1EEEvv
_ZN5doris8MemTable10_aggregateILb1ELb0EEEvv
Line
Count
Source
470
1.91k
void MemTable::_aggregate() {
471
1.91k
    SCOPED_RAW_TIMER(&_stat.agg_ns);
472
1.91k
    _stat.agg_times++;
473
1.91k
    vectorized::Block in_block = _input_mutable_block.to_block();
474
1.91k
    vectorized::MutableBlock mutable_block =
475
1.91k
            vectorized::MutableBlock::build_mutable_block(&in_block);
476
1.91k
    _vec_row_comparator->set_block(&mutable_block);
477
1.91k
    auto& block_data = in_block.get_columns_with_type_and_name();
478
1.91k
    DorisVector<RowInBlock*> temp_row_in_blocks;
479
1.91k
    temp_row_in_blocks.reserve(_last_sorted_pos);
480
1.91k
    RowInBlock* prev_row = nullptr;
481
1.91k
    int row_pos = -1;
482
    //only init agg if needed
483
484
1.91k
    auto init_for_agg = [&](RowInBlock* row) {
485
1.91k
        row->init_agg_places(_arena->aligned_alloc(_total_size_of_aggregate_states, 16),
486
1.91k
                             _offsets_of_aggregate_states.data());
487
1.91k
        for (auto cid = _tablet_schema->num_key_columns(); cid < _num_columns; cid++) {
488
1.91k
            auto* col_ptr = mutable_block.mutable_columns()[cid].get();
489
1.91k
            auto* data = prev_row->agg_places(cid);
490
1.91k
            _agg_functions[cid]->create(data);
491
1.91k
            _agg_functions[cid]->add(data, const_cast<const doris::vectorized::IColumn**>(&col_ptr),
492
1.91k
                                     prev_row->_row_pos, _arena.get());
493
1.91k
        }
494
1.91k
    };
495
496
1.91k
    if (!has_skip_bitmap_col || _seq_col_idx_in_block == -1) {
497
414k
        for (RowInBlock* cur_row : *_row_in_blocks) {
498
414k
            if (!temp_row_in_blocks.empty() && (*_vec_row_comparator)(prev_row, cur_row) == 0) {
499
95.0k
                if (!prev_row->has_init_agg()) {
500
6.81k
                    init_for_agg(prev_row);
501
6.81k
                }
502
95.0k
                _stat.merged_rows++;
503
95.0k
                _aggregate_two_row_in_block<has_skip_bitmap_col>(mutable_block, cur_row, prev_row);
504
319k
            } else {
505
319k
                prev_row = cur_row;
506
319k
                if (!temp_row_in_blocks.empty()) {
507
                    // no more rows to merge for prev row, finalize it
508
318k
                    _finalize_one_row<is_final>(temp_row_in_blocks.back(), block_data, row_pos);
509
318k
                }
510
319k
                temp_row_in_blocks.push_back(prev_row);
511
319k
                row_pos++;
512
319k
            }
513
414k
        }
514
1.91k
        if (!temp_row_in_blocks.empty()) {
515
            // finalize the last low
516
1.91k
            _finalize_one_row<is_final>(temp_row_in_blocks.back(), block_data, row_pos);
517
1.91k
        }
518
18.4E
    } else {
519
        // For flexible partial update and the table has sequence column, considering the following situation:
520
        // there are multiple rows with the same keys in memtable, some of them specify the sequence column,
521
        // some of them don't. We can't do the de-duplication in memtable becasue we can only know the value
522
        // of the sequence column of the row which don't specify seqeuence column in SegmentWriter after we
523
        // probe the historical data. So at here we can only merge rows that have sequence column together and
524
        // merge rows without sequence column together, and finally, perform deduplication on them in SegmentWriter.
525
526
        // !!ATTENTION!!: there may be rows with the same keys after MemTable::_aggregate() in this situation.
527
18.4E
        RowInBlock* row_with_seq_col = nullptr;
528
18.4E
        int row_pos_with_seq = -1;
529
18.4E
        RowInBlock* row_without_seq_col = nullptr;
530
18.4E
        int row_pos_without_seq = -1;
531
532
18.4E
        auto finalize_rows = [&]() {
533
18.4E
            if (row_with_seq_col != nullptr) {
534
18.4E
                _finalize_one_row<is_final>(row_with_seq_col, block_data, row_pos_with_seq);
535
18.4E
                row_with_seq_col = nullptr;
536
18.4E
            }
537
18.4E
            if (row_without_seq_col != nullptr) {
538
18.4E
                _finalize_one_row<is_final>(row_without_seq_col, block_data, row_pos_without_seq);
539
18.4E
                row_without_seq_col = nullptr;
540
18.4E
            }
541
18.4E
        };
542
18.4E
        auto add_row = [&](RowInBlock* row, bool with_seq_col) {
543
18.4E
            temp_row_in_blocks.push_back(row);
544
18.4E
            row_pos++;
545
18.4E
            if (with_seq_col) {
546
18.4E
                row_with_seq_col = row;
547
18.4E
                row_pos_with_seq = row_pos;
548
18.4E
            } else {
549
18.4E
                row_without_seq_col = row;
550
18.4E
                row_pos_without_seq = row_pos;
551
18.4E
            }
552
18.4E
        };
553
18.4E
        auto& skip_bitmaps = assert_cast<vectorized::ColumnBitmap*>(
554
18.4E
                                     mutable_block.mutable_columns()[_skip_bitmap_col_idx].get())
555
18.4E
                                     ->get_data();
556
18.4E
        for (auto* cur_row : *_row_in_blocks) {
557
0
            const BitmapValue& skip_bitmap = skip_bitmaps[cur_row->_row_pos];
558
0
            bool with_seq_col = !skip_bitmap.contains(_seq_col_unique_id);
559
            // compare keys, the keys of row_with_seq_col and row_with_seq_col is the same,
560
            // choose any of them if it's valid
561
0
            prev_row = (row_with_seq_col == nullptr) ? row_without_seq_col : row_with_seq_col;
562
0
            if (prev_row != nullptr && (*_vec_row_comparator)(prev_row, cur_row) == 0) {
563
0
                prev_row = (with_seq_col ? row_with_seq_col : row_without_seq_col);
564
0
                if (prev_row == nullptr) {
565
0
                    add_row(cur_row, with_seq_col);
566
0
                    continue;
567
0
                }
568
0
                if (!prev_row->has_init_agg()) {
569
0
                    init_for_agg(prev_row);
570
0
                }
571
0
                _stat.merged_rows++;
572
0
                _aggregate_two_row_in_block<has_skip_bitmap_col>(mutable_block, cur_row, prev_row);
573
0
            } else {
574
                // no more rows to merge for prev rows, finalize them
575
0
                finalize_rows();
576
0
                add_row(cur_row, with_seq_col);
577
0
            }
578
0
        }
579
        // finalize the last lows
580
18.4E
        finalize_rows();
581
18.4E
    }
582
1.91k
    if constexpr (!is_final) {
583
        // if is not final, we collect the agg results to input_block and then continue to insert
584
1.91k
        _input_mutable_block.swap(_output_mutable_block);
585
        //TODO(weixang):opt here.
586
1.91k
        std::unique_ptr<vectorized::Block> empty_input_block = in_block.create_same_struct_block(0);
587
1.91k
        _output_mutable_block =
588
1.91k
                vectorized::MutableBlock::build_mutable_block(empty_input_block.get());
589
1.91k
        _output_mutable_block.clear_column_data();
590
1.91k
        *_row_in_blocks = temp_row_in_blocks;
591
1.91k
        _last_sorted_pos = _row_in_blocks->size();
592
1.91k
    }
593
1.91k
}
_ZN5doris8MemTable10_aggregateILb1ELb1EEEvv
Line
Count
Source
470
174
void MemTable::_aggregate() {
471
174
    SCOPED_RAW_TIMER(&_stat.agg_ns);
472
174
    _stat.agg_times++;
473
174
    vectorized::Block in_block = _input_mutable_block.to_block();
474
174
    vectorized::MutableBlock mutable_block =
475
174
            vectorized::MutableBlock::build_mutable_block(&in_block);
476
174
    _vec_row_comparator->set_block(&mutable_block);
477
174
    auto& block_data = in_block.get_columns_with_type_and_name();
478
174
    DorisVector<RowInBlock*> temp_row_in_blocks;
479
174
    temp_row_in_blocks.reserve(_last_sorted_pos);
480
174
    RowInBlock* prev_row = nullptr;
481
174
    int row_pos = -1;
482
    //only init agg if needed
483
484
174
    auto init_for_agg = [&](RowInBlock* row) {
485
174
        row->init_agg_places(_arena->aligned_alloc(_total_size_of_aggregate_states, 16),
486
174
                             _offsets_of_aggregate_states.data());
487
174
        for (auto cid = _tablet_schema->num_key_columns(); cid < _num_columns; cid++) {
488
174
            auto* col_ptr = mutable_block.mutable_columns()[cid].get();
489
174
            auto* data = prev_row->agg_places(cid);
490
174
            _agg_functions[cid]->create(data);
491
174
            _agg_functions[cid]->add(data, const_cast<const doris::vectorized::IColumn**>(&col_ptr),
492
174
                                     prev_row->_row_pos, _arena.get());
493
174
        }
494
174
    };
495
496
174
    if (!has_skip_bitmap_col || _seq_col_idx_in_block == -1) {
497
5.68k
        for (RowInBlock* cur_row : *_row_in_blocks) {
498
5.68k
            if (!temp_row_in_blocks.empty() && (*_vec_row_comparator)(prev_row, cur_row) == 0) {
499
3.94k
                if (!prev_row->has_init_agg()) {
500
1.43k
                    init_for_agg(prev_row);
501
1.43k
                }
502
3.94k
                _stat.merged_rows++;
503
3.94k
                _aggregate_two_row_in_block<has_skip_bitmap_col>(mutable_block, cur_row, prev_row);
504
3.94k
            } else {
505
1.74k
                prev_row = cur_row;
506
1.74k
                if (!temp_row_in_blocks.empty()) {
507
                    // no more rows to merge for prev row, finalize it
508
1.58k
                    _finalize_one_row<is_final>(temp_row_in_blocks.back(), block_data, row_pos);
509
1.58k
                }
510
1.74k
                temp_row_in_blocks.push_back(prev_row);
511
1.74k
                row_pos++;
512
1.74k
            }
513
5.68k
        }
514
158
        if (!temp_row_in_blocks.empty()) {
515
            // finalize the last low
516
158
            _finalize_one_row<is_final>(temp_row_in_blocks.back(), block_data, row_pos);
517
158
        }
518
158
    } else {
519
        // For flexible partial update and the table has sequence column, considering the following situation:
520
        // there are multiple rows with the same keys in memtable, some of them specify the sequence column,
521
        // some of them don't. We can't do the de-duplication in memtable becasue we can only know the value
522
        // of the sequence column of the row which don't specify seqeuence column in SegmentWriter after we
523
        // probe the historical data. So at here we can only merge rows that have sequence column together and
524
        // merge rows without sequence column together, and finally, perform deduplication on them in SegmentWriter.
525
526
        // !!ATTENTION!!: there may be rows with the same keys after MemTable::_aggregate() in this situation.
527
16
        RowInBlock* row_with_seq_col = nullptr;
528
16
        int row_pos_with_seq = -1;
529
16
        RowInBlock* row_without_seq_col = nullptr;
530
16
        int row_pos_without_seq = -1;
531
532
16
        auto finalize_rows = [&]() {
533
16
            if (row_with_seq_col != nullptr) {
534
16
                _finalize_one_row<is_final>(row_with_seq_col, block_data, row_pos_with_seq);
535
16
                row_with_seq_col = nullptr;
536
16
            }
537
16
            if (row_without_seq_col != nullptr) {
538
16
                _finalize_one_row<is_final>(row_without_seq_col, block_data, row_pos_without_seq);
539
16
                row_without_seq_col = nullptr;
540
16
            }
541
16
        };
542
16
        auto add_row = [&](RowInBlock* row, bool with_seq_col) {
543
16
            temp_row_in_blocks.push_back(row);
544
16
            row_pos++;
545
16
            if (with_seq_col) {
546
16
                row_with_seq_col = row;
547
16
                row_pos_with_seq = row_pos;
548
16
            } else {
549
16
                row_without_seq_col = row;
550
16
                row_pos_without_seq = row_pos;
551
16
            }
552
16
        };
553
16
        auto& skip_bitmaps = assert_cast<vectorized::ColumnBitmap*>(
554
16
                                     mutable_block.mutable_columns()[_skip_bitmap_col_idx].get())
555
16
                                     ->get_data();
556
284
        for (auto* cur_row : *_row_in_blocks) {
557
284
            const BitmapValue& skip_bitmap = skip_bitmaps[cur_row->_row_pos];
558
284
            bool with_seq_col = !skip_bitmap.contains(_seq_col_unique_id);
559
            // compare keys, the keys of row_with_seq_col and row_with_seq_col is the same,
560
            // choose any of them if it's valid
561
284
            prev_row = (row_with_seq_col == nullptr) ? row_without_seq_col : row_with_seq_col;
562
284
            if (prev_row != nullptr && (*_vec_row_comparator)(prev_row, cur_row) == 0) {
563
220
                prev_row = (with_seq_col ? row_with_seq_col : row_without_seq_col);
564
220
                if (prev_row == nullptr) {
565
64
                    add_row(cur_row, with_seq_col);
566
64
                    continue;
567
64
                }
568
156
                if (!prev_row->has_init_agg()) {
569
72
                    init_for_agg(prev_row);
570
72
                }
571
156
                _stat.merged_rows++;
572
156
                _aggregate_two_row_in_block<has_skip_bitmap_col>(mutable_block, cur_row, prev_row);
573
156
            } else {
574
                // no more rows to merge for prev rows, finalize them
575
64
                finalize_rows();
576
64
                add_row(cur_row, with_seq_col);
577
64
            }
578
284
        }
579
        // finalize the last lows
580
16
        finalize_rows();
581
16
    }
582
174
    if constexpr (!is_final) {
583
        // if is not final, we collect the agg results to input_block and then continue to insert
584
174
        _input_mutable_block.swap(_output_mutable_block);
585
        //TODO(weixang):opt here.
586
174
        std::unique_ptr<vectorized::Block> empty_input_block = in_block.create_same_struct_block(0);
587
174
        _output_mutable_block =
588
174
                vectorized::MutableBlock::build_mutable_block(empty_input_block.get());
589
174
        _output_mutable_block.clear_column_data();
590
174
        *_row_in_blocks = temp_row_in_blocks;
591
174
        _last_sorted_pos = _row_in_blocks->size();
592
174
    }
593
174
}
594
595
0
void MemTable::shrink_memtable_by_agg() {
596
0
    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(
597
0
            _resource_ctx->memory_context()->mem_tracker()->write_tracker());
598
0
    SCOPED_CONSUME_MEM_TRACKER(_mem_tracker);
599
0
    if (_keys_type == KeysType::DUP_KEYS) {
600
0
        return;
601
0
    }
602
0
    size_t same_keys_num = _sort();
603
0
    if (same_keys_num != 0) {
604
0
        (_skip_bitmap_col_idx == -1) ? _aggregate<false, false>() : _aggregate<false, true>();
605
0
    }
606
0
}
607
608
134k
bool MemTable::need_flush() const {
609
134k
    DBUG_EXECUTE_IF("MemTable.need_flush", { return true; });
610
134k
    auto max_size = config::write_buffer_size;
611
134k
    if (_partial_update_mode == UniqueKeyUpdateModePB::UPDATE_FIXED_COLUMNS) {
612
943
        auto update_columns_size = _num_columns;
613
943
        max_size = max_size * update_columns_size / _tablet_schema->num_columns();
614
943
        max_size = max_size > 1048576 ? max_size : 1048576;
615
943
    }
616
134k
    return memory_usage() >= max_size;
617
134k
}
618
619
134k
bool MemTable::need_agg() const {
620
134k
    if (_keys_type == KeysType::AGG_KEYS) {
621
4.38k
        auto max_size = config::write_buffer_size_for_agg;
622
4.38k
        return memory_usage() >= max_size;
623
4.38k
    }
624
130k
    return false;
625
134k
}
626
627
63.4k
size_t MemTable::get_flush_reserve_memory_size() const {
628
63.4k
    if (_keys_type == KeysType::DUP_KEYS && _tablet_schema->num_key_columns() == 0) {
629
22
        return 0; // no need to reserve
630
22
    }
631
63.4k
    return static_cast<size_t>(static_cast<double>(_input_mutable_block.allocated_bytes()) * 1.2);
632
63.4k
}
633
634
63.4k
Status MemTable::_to_block(std::unique_ptr<vectorized::Block>* res) {
635
63.4k
    size_t same_keys_num = _sort();
636
63.4k
    if (_keys_type == KeysType::DUP_KEYS || same_keys_num == 0) {
637
61.3k
        if (_keys_type == KeysType::DUP_KEYS && _tablet_schema->num_key_columns() == 0) {
638
22
            _output_mutable_block.swap(_input_mutable_block);
639
61.3k
        } else {
640
61.3k
            vectorized::Block in_block = _input_mutable_block.to_block();
641
61.3k
            RETURN_IF_ERROR(_put_into_output(in_block));
642
61.3k
        }
643
61.3k
    } else {
644
2.08k
        (_skip_bitmap_col_idx == -1) ? _aggregate<true, false>() : _aggregate<true, true>();
645
2.08k
    }
646
63.4k
    if (_keys_type == KeysType::UNIQUE_KEYS && _enable_unique_key_mow &&
647
63.4k
        !_tablet_schema->cluster_key_uids().empty()) {
648
1.55k
        if (_partial_update_mode != UniqueKeyUpdateModePB::UPSERT) {
649
0
            return Status::InternalError(
650
0
                    "Partial update for mow with cluster keys is not supported");
651
0
        }
652
1.55k
        RETURN_IF_ERROR(_sort_by_cluster_keys());
653
1.55k
    }
654
63.4k
    _input_mutable_block.clear();
655
63.4k
    *res = vectorized::Block::create_unique(_output_mutable_block.to_block());
656
63.4k
    return Status::OK();
657
63.4k
}
658
659
63.4k
Status MemTable::to_block(std::unique_ptr<vectorized::Block>* res) {
660
63.4k
    RETURN_IF_ERROR_OR_CATCH_EXCEPTION(_to_block(res));
661
63.4k
    return Status::OK();
662
63.4k
}
663
664
#include "common/compile_check_end.h"
665
} // namespace doris