Coverage Report

Created: 2025-04-29 20:56

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