Coverage Report

Created: 2025-04-30 06:12

/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
162k
          _total_size_of_aggregate_states(0) {
63
162k
    g_memtable_cnt << 1;
64
162k
    _resource_ctx = thread_context()->resource_ctx();
65
162k
    _mem_tracker = std::make_shared<MemTracker>();
66
162k
    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(
67
162k
            _resource_ctx->memory_context()->mem_tracker()->write_tracker());
68
162k
    SCOPED_CONSUME_MEM_TRACKER(_mem_tracker);
69
162k
    _arena = std::make_unique<vectorized::Arena>();
70
162k
    _vec_row_comparator = std::make_shared<RowInBlockComparator>(_tablet_schema);
71
162k
    _num_columns = _tablet_schema->num_columns();
72
162k
    if (partial_update_info != nullptr) {
73
162k
        _partial_update_mode = partial_update_info->update_mode();
74
162k
        if (_partial_update_mode == UniqueKeyUpdateModePB::UPDATE_FIXED_COLUMNS) {
75
5.03k
            _num_columns = partial_update_info->partial_update_input_columns.size();
76
5.03k
            if (partial_update_info->is_schema_contains_auto_inc_column &&
77
5.03k
                !partial_update_info->is_input_columns_contains_auto_inc_column) {
78
386
                _is_partial_update_and_auto_inc = true;
79
386
                _num_columns += 1;
80
386
            }
81
5.03k
        }
82
162k
    }
83
    // TODO: Support ZOrderComparator in the future
84
162k
    _init_columns_offset_by_slot_descs(slot_descs, tuple_desc);
85
162k
    _row_in_blocks = std::make_unique<DorisVector<RowInBlock*>>();
86
162k
}
87
88
void MemTable::_init_columns_offset_by_slot_descs(const std::vector<SlotDescriptor*>* slot_descs,
89
162k
                                                  const TupleDescriptor* tuple_desc) {
90
2.32M
    for (auto slot_desc : *slot_descs) {
91
2.32M
        const auto& slots = tuple_desc->slots();
92
34.6M
        for (int j = 0; j < slots.size(); ++j) {
93
34.6M
            if (slot_desc->id() == slots[j]->id()) {
94
2.32M
                _column_offset.emplace_back(j);
95
2.32M
                break;
96
2.32M
            }
97
34.6M
        }
98
2.32M
    }
99
162k
    if (_is_partial_update_and_auto_inc) {
100
386
        _column_offset.emplace_back(_column_offset.size());
101
386
    }
102
162k
}
103
104
59.9k
void MemTable::_init_agg_functions(const vectorized::Block* block) {
105
711k
    for (auto cid = _tablet_schema->num_key_columns(); cid < _num_columns; ++cid) {
106
651k
        vectorized::AggregateFunctionPtr function;
107
651k
        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
548k
            if (_skip_bitmap_col_idx != cid) {
111
547k
                function = vectorized::AggregateFunctionSimpleFactory::instance().get(
112
547k
                        "replace_load", {block->get_data_type(cid)},
113
547k
                        block->get_data_type(cid)->is_nullable(),
114
547k
                        BeExecVersionManager::get_newest_version());
115
547k
            } else {
116
556
                function = vectorized::AggregateFunctionSimpleFactory::instance().get(
117
556
                        "bitmap_intersect", {block->get_data_type(cid)}, false,
118
556
                        BeExecVersionManager::get_newest_version());
119
556
            }
120
548k
        } else {
121
102k
            function = _tablet_schema->column(cid).get_aggregate_function(
122
102k
                    vectorized::AGG_LOAD_SUFFIX, _tablet_schema->column(cid).get_be_exec_version());
123
102k
            if (function == nullptr) {
124
0
                LOG(WARNING) << "column get aggregate function failed, column="
125
0
                             << _tablet_schema->column(cid).name();
126
0
            }
127
102k
        }
128
129
651k
        DCHECK(function != nullptr);
130
651k
        _agg_functions[cid] = function;
131
651k
    }
132
133
711k
    for (auto cid = _tablet_schema->num_key_columns(); cid < _num_columns; ++cid) {
134
651k
        _offsets_of_aggregate_states[cid] = _total_size_of_aggregate_states;
135
651k
        _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
651k
        if (cid + 1 < _num_columns) {
139
591k
            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
591k
            _total_size_of_aggregate_states =
144
591k
                    (_total_size_of_aggregate_states + alignment_of_next_state - 1) /
145
591k
                    alignment_of_next_state * alignment_of_next_state;
146
591k
        }
147
651k
    }
148
59.9k
}
149
150
162k
MemTable::~MemTable() {
151
162k
    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(
152
162k
            _resource_ctx->memory_context()->mem_tracker()->write_tracker());
153
162k
    {
154
162k
        SCOPED_CONSUME_MEM_TRACKER(_mem_tracker);
155
162k
        g_memtable_cnt << -1;
156
162k
        if (_keys_type != KeysType::DUP_KEYS) {
157
28.0M
            for (auto it = _row_in_blocks->begin(); it != _row_in_blocks->end(); it++) {
158
28.0M
                if (!(*it)->has_init_agg()) {
159
28.0M
                    continue;
160
28.0M
                }
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
86.3k
        }
170
171
162k
        std::for_each(_row_in_blocks->begin(), _row_in_blocks->end(),
172
162k
                      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
162k
        _arena.reset();
176
162k
        _vec_row_comparator.reset();
177
162k
        _row_in_blocks.reset();
178
162k
        _agg_functions.clear();
179
162k
        _input_mutable_block.clear();
180
162k
        _output_mutable_block.clear();
181
162k
    }
182
162k
    if (_is_flush_success) {
183
        // If the memtable is flush success, then its memtracker's consumption should be 0
184
121k
        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
121k
    }
189
162k
}
190
191
838k
int RowInBlockComparator::operator()(const RowInBlock* left, const RowInBlock* right) const {
192
838k
    return _pblock->compare_at(left->_row_pos, right->_row_pos, _tablet_schema->num_key_columns(),
193
838k
                               *_pblock, -1);
194
838k
}
195
196
Status MemTable::insert(const vectorized::Block* input_block,
197
273k
                        const DorisVector<uint32_t>& row_idxs) {
198
273k
    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(
199
273k
            _resource_ctx->memory_context()->mem_tracker()->write_tracker());
200
273k
    SCOPED_CONSUME_MEM_TRACKER(_mem_tracker);
201
202
273k
    if (_is_first_insertion) {
203
121k
        _is_first_insertion = false;
204
121k
        auto clone_block = input_block->clone_without_columns(&_column_offset);
205
121k
        _input_mutable_block = vectorized::MutableBlock::build_mutable_block(&clone_block);
206
121k
        _vec_row_comparator->set_block(&_input_mutable_block);
207
121k
        _output_mutable_block = vectorized::MutableBlock::build_mutable_block(&clone_block);
208
121k
        if (_tablet_schema->has_sequence_col()) {
209
2.36k
            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
1.02k
                for (int32_t i = 0; i < clone_block.columns(); i++) {
213
822
                    if (clone_block.get_by_position(i).name == SEQUENCE_COL) {
214
76
                        _seq_col_idx_in_block = i;
215
76
                        break;
216
76
                    }
217
822
                }
218
2.08k
            } else {
219
2.08k
                _seq_col_idx_in_block = _tablet_schema->sequence_col_idx();
220
2.08k
            }
221
2.36k
        }
222
121k
        if (_partial_update_mode == UniqueKeyUpdateModePB::UPDATE_FLEXIBLE_COLUMNS &&
223
121k
            _tablet_schema->has_skip_bitmap_col()) {
224
            // init of _skip_bitmap_col_idx must be before _init_agg_functions()
225
556
            _skip_bitmap_col_idx = _tablet_schema->skip_bitmap_col_idx();
226
556
            if (_seq_col_idx_in_block != -1) {
227
48
                _seq_col_unique_id = _tablet_schema->column(_seq_col_idx_in_block).unique_id();
228
48
            }
229
556
        }
230
121k
        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
59.9k
            RETURN_IF_CATCH_EXCEPTION(_init_agg_functions(&clone_block));
234
59.9k
        }
235
121k
    }
236
237
273k
    auto num_rows = row_idxs.size();
238
273k
    size_t cursor_in_mutableblock = _input_mutable_block.rows();
239
273k
    RETURN_IF_ERROR(_input_mutable_block.add_rows(input_block, row_idxs.data(),
240
273k
                                                  row_idxs.data() + num_rows, &_column_offset));
241
72.7M
    for (int i = 0; i < num_rows; i++) {
242
72.4M
        _row_in_blocks->emplace_back(new RowInBlock {cursor_in_mutableblock + i});
243
72.4M
    }
244
245
273k
    _stat.raw_rows += num_rows;
246
273k
    return Status::OK();
247
273k
}
248
249
template <bool has_skip_bitmap_col>
250
void MemTable::_aggregate_two_row_in_block(vectorized::MutableBlock& mutable_block,
251
198k
                                           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
198k
    if (_tablet_schema->has_sequence_col() && _seq_col_idx_in_block >= 0) {
256
649
        DCHECK_LT(_seq_col_idx_in_block, mutable_block.columns());
257
649
        auto col_ptr = mutable_block.mutable_columns()[_seq_col_idx_in_block].get();
258
649
        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
649
        if (res > 0) {
261
209
            return;
262
209
        }
263
        // need to update the row pos in dst row to the src row pos when has
264
        // sequence column
265
440
        dst_row->_row_pos = src_row->_row_pos;
266
440
    }
267
    // dst is non-sequence row, or dst sequence is smaller
268
198k
    if constexpr (!has_skip_bitmap_col) {
269
8.16k
        DCHECK(_skip_bitmap_col_idx == -1);
270
805k
        for (size_t cid = _tablet_schema->num_key_columns(); cid < _num_columns; ++cid) {
271
615k
            auto* col_ptr = mutable_block.mutable_columns()[cid].get();
272
615k
            _agg_functions[cid]->add(dst_row->agg_places(cid),
273
615k
                                     const_cast<const doris::vectorized::IColumn**>(&col_ptr),
274
615k
                                     src_row->_row_pos, _arena.get());
275
615k
        }
276
190k
    } else {
277
8.16k
        DCHECK(_skip_bitmap_col_idx != -1);
278
8.16k
        DCHECK_LT(_skip_bitmap_col_idx, mutable_block.columns());
279
8.16k
        const BitmapValue& skip_bitmap =
280
8.16k
                assert_cast<vectorized::ColumnBitmap*, TypeCheckOnRelease::DISABLE>(
281
8.16k
                        mutable_block.mutable_columns()[_skip_bitmap_col_idx].get())
282
8.16k
                        ->get_data()[src_row->_row_pos];
283
147k
        for (size_t cid = _tablet_schema->num_key_columns(); cid < _num_columns; ++cid) {
284
139k
            const auto& col = _tablet_schema->column(cid);
285
139k
            if (cid != _skip_bitmap_col_idx && skip_bitmap.contains(col.unique_id())) {
286
69.8k
                continue;
287
69.8k
            }
288
69.8k
            auto* col_ptr = mutable_block.mutable_columns()[cid].get();
289
69.8k
            _agg_functions[cid]->add(dst_row->agg_places(cid),
290
69.8k
                                     const_cast<const doris::vectorized::IColumn**>(&col_ptr),
291
69.8k
                                     src_row->_row_pos, _arena.get());
292
69.8k
        }
293
8.16k
    }
294
198k
}
_ZN5doris8MemTable27_aggregate_two_row_in_blockILb0EEEvRNS_10vectorized12MutableBlockEPNS_10RowInBlockES6_
Line
Count
Source
251
190k
                                           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
190k
    if (_tablet_schema->has_sequence_col() && _seq_col_idx_in_block >= 0) {
256
337
        DCHECK_LT(_seq_col_idx_in_block, mutable_block.columns());
257
337
        auto col_ptr = mutable_block.mutable_columns()[_seq_col_idx_in_block].get();
258
337
        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
337
        if (res > 0) {
261
173
            return;
262
173
        }
263
        // need to update the row pos in dst row to the src row pos when has
264
        // sequence column
265
164
        dst_row->_row_pos = src_row->_row_pos;
266
164
    }
267
    // dst is non-sequence row, or dst sequence is smaller
268
190k
    if constexpr (!has_skip_bitmap_col) {
269
190k
        DCHECK(_skip_bitmap_col_idx == -1);
270
805k
        for (size_t cid = _tablet_schema->num_key_columns(); cid < _num_columns; ++cid) {
271
615k
            auto* col_ptr = mutable_block.mutable_columns()[cid].get();
272
615k
            _agg_functions[cid]->add(dst_row->agg_places(cid),
273
615k
                                     const_cast<const doris::vectorized::IColumn**>(&col_ptr),
274
615k
                                     src_row->_row_pos, _arena.get());
275
615k
        }
276
190k
    } else {
277
190k
        DCHECK(_skip_bitmap_col_idx != -1);
278
190k
        DCHECK_LT(_skip_bitmap_col_idx, mutable_block.columns());
279
190k
        const BitmapValue& skip_bitmap =
280
190k
                assert_cast<vectorized::ColumnBitmap*, TypeCheckOnRelease::DISABLE>(
281
190k
                        mutable_block.mutable_columns()[_skip_bitmap_col_idx].get())
282
190k
                        ->get_data()[src_row->_row_pos];
283
190k
        for (size_t cid = _tablet_schema->num_key_columns(); cid < _num_columns; ++cid) {
284
190k
            const auto& col = _tablet_schema->column(cid);
285
190k
            if (cid != _skip_bitmap_col_idx && skip_bitmap.contains(col.unique_id())) {
286
190k
                continue;
287
190k
            }
288
190k
            auto* col_ptr = mutable_block.mutable_columns()[cid].get();
289
190k
            _agg_functions[cid]->add(dst_row->agg_places(cid),
290
190k
                                     const_cast<const doris::vectorized::IColumn**>(&col_ptr),
291
190k
                                     src_row->_row_pos, _arena.get());
292
190k
        }
293
190k
    }
294
190k
}
_ZN5doris8MemTable27_aggregate_two_row_in_blockILb1EEEvRNS_10vectorized12MutableBlockEPNS_10RowInBlockES6_
Line
Count
Source
251
8.19k
                                           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
8.19k
    if (_tablet_schema->has_sequence_col() && _seq_col_idx_in_block >= 0) {
256
312
        DCHECK_LT(_seq_col_idx_in_block, mutable_block.columns());
257
312
        auto col_ptr = mutable_block.mutable_columns()[_seq_col_idx_in_block].get();
258
312
        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
312
        if (res > 0) {
261
36
            return;
262
36
        }
263
        // need to update the row pos in dst row to the src row pos when has
264
        // sequence column
265
276
        dst_row->_row_pos = src_row->_row_pos;
266
276
    }
267
    // dst is non-sequence row, or dst sequence is smaller
268
8.16k
    if constexpr (!has_skip_bitmap_col) {
269
8.16k
        DCHECK(_skip_bitmap_col_idx == -1);
270
8.16k
        for (size_t cid = _tablet_schema->num_key_columns(); cid < _num_columns; ++cid) {
271
8.16k
            auto* col_ptr = mutable_block.mutable_columns()[cid].get();
272
8.16k
            _agg_functions[cid]->add(dst_row->agg_places(cid),
273
8.16k
                                     const_cast<const doris::vectorized::IColumn**>(&col_ptr),
274
8.16k
                                     src_row->_row_pos, _arena.get());
275
8.16k
        }
276
8.16k
    } else {
277
8.16k
        DCHECK(_skip_bitmap_col_idx != -1);
278
8.16k
        DCHECK_LT(_skip_bitmap_col_idx, mutable_block.columns());
279
8.16k
        const BitmapValue& skip_bitmap =
280
8.16k
                assert_cast<vectorized::ColumnBitmap*, TypeCheckOnRelease::DISABLE>(
281
8.16k
                        mutable_block.mutable_columns()[_skip_bitmap_col_idx].get())
282
8.16k
                        ->get_data()[src_row->_row_pos];
283
147k
        for (size_t cid = _tablet_schema->num_key_columns(); cid < _num_columns; ++cid) {
284
139k
            const auto& col = _tablet_schema->column(cid);
285
139k
            if (cid != _skip_bitmap_col_idx && skip_bitmap.contains(col.unique_id())) {
286
69.8k
                continue;
287
69.8k
            }
288
69.8k
            auto* col_ptr = mutable_block.mutable_columns()[cid].get();
289
69.8k
            _agg_functions[cid]->add(dst_row->agg_places(cid),
290
69.8k
                                     const_cast<const doris::vectorized::IColumn**>(&col_ptr),
291
69.8k
                                     src_row->_row_pos, _arena.get());
292
69.8k
        }
293
8.16k
    }
294
8.16k
}
295
116k
Status MemTable::_put_into_output(vectorized::Block& in_block) {
296
116k
    SCOPED_RAW_TIMER(&_stat.put_into_output_ns);
297
116k
    DorisVector<uint32_t> row_pos_vec;
298
116k
    DCHECK(in_block.rows() <= std::numeric_limits<int>::max());
299
116k
    row_pos_vec.reserve(in_block.rows());
300
70.5M
    for (int i = 0; i < _row_in_blocks->size(); i++) {
301
70.4M
        row_pos_vec.emplace_back((*_row_in_blocks)[i]->_row_pos);
302
70.4M
    }
303
116k
    return _output_mutable_block.add_rows(&in_block, row_pos_vec.data(),
304
116k
                                          row_pos_vec.data() + in_block.rows());
305
116k
}
306
307
121k
size_t MemTable::_sort() {
308
121k
    SCOPED_RAW_TIMER(&_stat.sort_ns);
309
121k
    _stat.sort_times++;
310
121k
    size_t same_keys_num = 0;
311
    // sort new rows
312
121k
    Tie tie = Tie(_last_sorted_pos, _row_in_blocks->size());
313
493k
    for (size_t i = 0; i < _tablet_schema->num_key_columns(); i++) {
314
699M
        auto cmp = [&](const RowInBlock* lhs, const RowInBlock* rhs) -> int {
315
699M
            return _input_mutable_block.compare_one_column(lhs->_row_pos, rhs->_row_pos, i, -1);
316
699M
        };
317
372k
        _sort_one_column(*_row_in_blocks, tie, cmp);
318
372k
    }
319
121k
    bool is_dup = (_keys_type == KeysType::DUP_KEYS);
320
    // sort extra round by _row_pos to make the sort stable
321
121k
    auto iter = tie.iter();
322
502k
    while (iter.next()) {
323
381k
        pdqsort(std::next(_row_in_blocks->begin(), iter.left()),
324
381k
                std::next(_row_in_blocks->begin(), iter.right()),
325
37.1M
                [&is_dup](const RowInBlock* lhs, const RowInBlock* rhs) -> bool {
326
37.1M
                    return is_dup ? lhs->_row_pos > rhs->_row_pos : lhs->_row_pos < rhs->_row_pos;
327
37.1M
                });
328
381k
        same_keys_num += iter.right() - iter.left();
329
381k
    }
330
    // merge new rows and old rows
331
121k
    _vec_row_comparator->set_block(&_input_mutable_block);
332
121k
    auto cmp_func = [this, is_dup, &same_keys_num](const RowInBlock* l,
333
121k
                                                   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
121k
    auto new_row_it = std::next(_row_in_blocks->begin(), _last_sorted_pos);
343
121k
    std::inplace_merge(_row_in_blocks->begin(), new_row_it, _row_in_blocks->end(), cmp_func);
344
121k
    _last_sorted_pos = _row_in_blocks->size();
345
121k
    return same_keys_num;
346
121k
}
347
348
3.10k
Status MemTable::_sort_by_cluster_keys() {
349
3.10k
    SCOPED_RAW_TIMER(&_stat.sort_ns);
350
3.10k
    _stat.sort_times++;
351
    // sort all rows
352
3.10k
    vectorized::Block in_block = _output_mutable_block.to_block();
353
3.10k
    vectorized::MutableBlock mutable_block =
354
3.10k
            vectorized::MutableBlock::build_mutable_block(&in_block);
355
3.10k
    auto clone_block = in_block.clone_without_columns();
356
3.10k
    _output_mutable_block = vectorized::MutableBlock::build_mutable_block(&clone_block);
357
358
3.10k
    DorisVector<RowInBlock*> row_in_blocks;
359
3.10k
    std::unique_ptr<int, std::function<void(int*)>> row_in_blocks_deleter((int*)0x01, [&](int*) {
360
3.10k
        std::for_each(row_in_blocks.begin(), row_in_blocks.end(),
361
3.10k
                      std::default_delete<RowInBlock>());
362
3.10k
    });
363
3.10k
    row_in_blocks.reserve(mutable_block.rows());
364
1.61M
    for (size_t i = 0; i < mutable_block.rows(); i++) {
365
1.60M
        row_in_blocks.emplace_back(new RowInBlock {i});
366
1.60M
    }
367
3.10k
    Tie tie = Tie(0, mutable_block.rows());
368
369
7.55k
    for (auto cid : _tablet_schema->cluster_key_uids()) {
370
7.55k
        auto index = _tablet_schema->field_index(cid);
371
7.55k
        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
16.7M
        auto cmp = [&](const RowInBlock* lhs, const RowInBlock* rhs) -> int {
376
16.7M
            return mutable_block.compare_one_column(lhs->_row_pos, rhs->_row_pos, index, -1);
377
16.7M
        };
378
7.55k
        _sort_one_column(row_in_blocks, tie, cmp);
379
7.55k
    }
380
381
    // sort extra round by _row_pos to make the sort stable
382
3.10k
    auto iter = tie.iter();
383
238k
    while (iter.next()) {
384
235k
        pdqsort(std::next(row_in_blocks.begin(), iter.left()),
385
235k
                std::next(row_in_blocks.begin(), iter.right()),
386
1.69M
                [](const RowInBlock* lhs, const RowInBlock* rhs) -> bool {
387
1.69M
                    return lhs->_row_pos < rhs->_row_pos;
388
1.69M
                });
389
235k
    }
390
391
3.10k
    in_block = mutable_block.to_block();
392
3.10k
    SCOPED_RAW_TIMER(&_stat.put_into_output_ns);
393
3.10k
    DorisVector<uint32_t> row_pos_vec;
394
3.10k
    DCHECK(in_block.rows() <= std::numeric_limits<int>::max());
395
3.10k
    row_pos_vec.reserve(in_block.rows());
396
1.63M
    for (int i = 0; i < row_in_blocks.size(); i++) {
397
1.63M
        row_pos_vec.emplace_back(row_in_blocks[i]->_row_pos);
398
1.63M
    }
399
3.10k
    std::vector<int> column_offset;
400
43.0k
    for (int i = 0; i < _column_offset.size(); ++i) {
401
39.9k
        column_offset.emplace_back(i);
402
39.9k
    }
403
3.10k
    return _output_mutable_block.add_rows(&in_block, row_pos_vec.data(),
404
3.10k
                                          row_pos_vec.data() + in_block.rows(), &column_offset);
405
3.10k
}
406
407
void MemTable::_sort_one_column(DorisVector<RowInBlock*>& row_in_blocks, Tie& tie,
408
379k
                                std::function<int(const RowInBlock*, const RowInBlock*)> cmp) {
409
379k
    auto iter = tie.iter();
410
11.8M
    while (iter.next()) {
411
11.4M
        pdqsort(std::next(row_in_blocks.begin(), static_cast<int>(iter.left())),
412
11.4M
                std::next(row_in_blocks.begin(), static_cast<int>(iter.right())),
413
551M
                [&cmp](auto lhs, auto rhs) -> bool { return cmp(lhs, rhs) < 0; });
414
11.4M
        tie[iter.left()] = 0;
415
123M
        for (auto i = iter.left() + 1; i < iter.right(); i++) {
416
111M
            tie[i] = (cmp(row_in_blocks[i - 1], row_in_blocks[i]) == 0);
417
111M
        }
418
11.4M
    }
419
379k
}
420
421
template <bool is_final>
422
void MemTable::_finalize_one_row(RowInBlock* row,
423
                                 const vectorized::ColumnsWithTypeAndName& block_data,
424
643k
                                 int row_pos) {
425
    // move key columns
426
1.69M
    for (size_t i = 0; i < _tablet_schema->num_key_columns(); ++i) {
427
1.04M
        _output_mutable_block.get_column_by_position(i)->insert_from(*block_data[i].column.get(),
428
1.04M
                                                                     row->_row_pos);
429
1.04M
    }
430
643k
    if (row->has_init_agg()) {
431
        // get value columns from agg_places
432
169k
        for (size_t i = _tablet_schema->num_key_columns(); i < _num_columns; ++i) {
433
153k
            auto function = _agg_functions[i];
434
153k
            auto* agg_place = row->agg_places(i);
435
153k
            auto* col_ptr = _output_mutable_block.get_column_by_position(i).get();
436
153k
            function->insert_result_into(agg_place, *col_ptr);
437
438
153k
            if constexpr (is_final) {
439
0
                function->destroy(agg_place);
440
0
            } else {
441
0
                function->reset(agg_place);
442
0
            }
443
153k
        }
444
445
16.6k
        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
627k
    } else {
457
        // move columns for rows do not need agg
458
11.4M
        for (size_t i = _tablet_schema->num_key_columns(); i < _num_columns; ++i) {
459
10.8M
            _output_mutable_block.get_column_by_position(i)->insert_from(
460
10.8M
                    *block_data[i].column.get(), row->_row_pos);
461
10.8M
        }
462
627k
    }
463
643k
    if constexpr (!is_final) {
464
0
        row->_row_pos = row_pos;
465
0
    }
466
643k
}
Unexecuted instantiation: _ZN5doris8MemTable17_finalize_one_rowILb0EEEvPNS_10RowInBlockERKSt6vectorINS_10vectorized21ColumnWithTypeAndNameESaIS6_EEi
_ZN5doris8MemTable17_finalize_one_rowILb1EEEvPNS_10RowInBlockERKSt6vectorINS_10vectorized21ColumnWithTypeAndNameESaIS6_EEi
Line
Count
Source
424
643k
                                 int row_pos) {
425
    // move key columns
426
1.69M
    for (size_t i = 0; i < _tablet_schema->num_key_columns(); ++i) {
427
1.04M
        _output_mutable_block.get_column_by_position(i)->insert_from(*block_data[i].column.get(),
428
1.04M
                                                                     row->_row_pos);
429
1.04M
    }
430
643k
    if (row->has_init_agg()) {
431
        // get value columns from agg_places
432
169k
        for (size_t i = _tablet_schema->num_key_columns(); i < _num_columns; ++i) {
433
153k
            auto function = _agg_functions[i];
434
153k
            auto* agg_place = row->agg_places(i);
435
153k
            auto* col_ptr = _output_mutable_block.get_column_by_position(i).get();
436
153k
            function->insert_result_into(agg_place, *col_ptr);
437
438
153k
            if constexpr (is_final) {
439
153k
                function->destroy(agg_place);
440
153k
            } else {
441
153k
                function->reset(agg_place);
442
153k
            }
443
153k
        }
444
445
16.6k
        if constexpr (is_final) {
446
16.6k
            row->remove_init_agg();
447
16.6k
        } else {
448
16.6k
            for (size_t i = _tablet_schema->num_key_columns(); i < _num_columns; ++i) {
449
16.6k
                auto function = _agg_functions[i];
450
16.6k
                auto* agg_place = row->agg_places(i);
451
16.6k
                auto* col_ptr = _output_mutable_block.get_column_by_position(i).get();
452
16.6k
                function->add(agg_place, const_cast<const doris::vectorized::IColumn**>(&col_ptr),
453
16.6k
                              row_pos, _arena.get());
454
16.6k
            }
455
16.6k
        }
456
627k
    } else {
457
        // move columns for rows do not need agg
458
11.4M
        for (size_t i = _tablet_schema->num_key_columns(); i < _num_columns; ++i) {
459
10.8M
            _output_mutable_block.get_column_by_position(i)->insert_from(
460
10.8M
                    *block_data[i].column.get(), row->_row_pos);
461
10.8M
        }
462
627k
    }
463
643k
    if constexpr (!is_final) {
464
643k
        row->_row_pos = row_pos;
465
643k
    }
466
643k
}
467
468
template <bool is_final, bool has_skip_bitmap_col>
469
4.18k
void MemTable::_aggregate() {
470
4.18k
    SCOPED_RAW_TIMER(&_stat.agg_ns);
471
4.18k
    _stat.agg_times++;
472
4.18k
    vectorized::Block in_block = _input_mutable_block.to_block();
473
4.18k
    vectorized::MutableBlock mutable_block =
474
4.18k
            vectorized::MutableBlock::build_mutable_block(&in_block);
475
4.18k
    _vec_row_comparator->set_block(&mutable_block);
476
4.18k
    auto& block_data = in_block.get_columns_with_type_and_name();
477
4.18k
    DorisVector<RowInBlock*> temp_row_in_blocks;
478
4.18k
    temp_row_in_blocks.reserve(_last_sorted_pos);
479
4.18k
    RowInBlock* prev_row = nullptr;
480
4.18k
    int row_pos = -1;
481
    //only init agg if needed
482
483
16.6k
    auto init_for_agg = [&](RowInBlock* row) {
484
16.6k
        row->init_agg_places(_arena->aligned_alloc(_total_size_of_aggregate_states, 16),
485
16.6k
                             _offsets_of_aggregate_states.data());
486
169k
        for (auto cid = _tablet_schema->num_key_columns(); cid < _num_columns; cid++) {
487
153k
            auto* col_ptr = mutable_block.mutable_columns()[cid].get();
488
153k
            auto* data = prev_row->agg_places(cid);
489
153k
            _agg_functions[cid]->create(data);
490
153k
            _agg_functions[cid]->add(data, const_cast<const doris::vectorized::IColumn**>(&col_ptr),
491
153k
                                     prev_row->_row_pos, _arena.get());
492
153k
        }
493
16.6k
    };
Unexecuted instantiation: _ZZN5doris8MemTable10_aggregateILb0ELb0EEEvvENKUlPNS_10RowInBlockEE_clES3_
Unexecuted instantiation: _ZZN5doris8MemTable10_aggregateILb0ELb1EEEvvENKUlPNS_10RowInBlockEE_clES3_
_ZZN5doris8MemTable10_aggregateILb1ELb0EEEvvENKUlPNS_10RowInBlockEE_clES3_
Line
Count
Source
483
13.6k
    auto init_for_agg = [&](RowInBlock* row) {
484
13.6k
        row->init_agg_places(_arena->aligned_alloc(_total_size_of_aggregate_states, 16),
485
13.6k
                             _offsets_of_aggregate_states.data());
486
115k
        for (auto cid = _tablet_schema->num_key_columns(); cid < _num_columns; cid++) {
487
101k
            auto* col_ptr = mutable_block.mutable_columns()[cid].get();
488
101k
            auto* data = prev_row->agg_places(cid);
489
101k
            _agg_functions[cid]->create(data);
490
101k
            _agg_functions[cid]->add(data, const_cast<const doris::vectorized::IColumn**>(&col_ptr),
491
101k
                                     prev_row->_row_pos, _arena.get());
492
101k
        }
493
13.6k
    };
_ZZN5doris8MemTable10_aggregateILb1ELb1EEEvvENKUlPNS_10RowInBlockEE_clES3_
Line
Count
Source
483
3.00k
    auto init_for_agg = [&](RowInBlock* row) {
484
3.00k
        row->init_agg_places(_arena->aligned_alloc(_total_size_of_aggregate_states, 16),
485
3.00k
                             _offsets_of_aggregate_states.data());
486
54.0k
        for (auto cid = _tablet_schema->num_key_columns(); cid < _num_columns; cid++) {
487
51.0k
            auto* col_ptr = mutable_block.mutable_columns()[cid].get();
488
51.0k
            auto* data = prev_row->agg_places(cid);
489
51.0k
            _agg_functions[cid]->create(data);
490
51.0k
            _agg_functions[cid]->add(data, const_cast<const doris::vectorized::IColumn**>(&col_ptr),
491
51.0k
                                     prev_row->_row_pos, _arena.get());
492
51.0k
        }
493
3.00k
    };
494
495
4.18k
    if (!has_skip_bitmap_col || _seq_col_idx_in_block == -1) {
496
841k
        for (RowInBlock* cur_row : *_row_in_blocks) {
497
841k
            if (!temp_row_in_blocks.empty() && (*_vec_row_comparator)(prev_row, cur_row) == 0) {
498
198k
                if (!prev_row->has_init_agg()) {
499
16.5k
                    init_for_agg(prev_row);
500
16.5k
                }
501
198k
                _stat.merged_rows++;
502
198k
                _aggregate_two_row_in_block<has_skip_bitmap_col>(mutable_block, cur_row, prev_row);
503
643k
            } else {
504
643k
                prev_row = cur_row;
505
643k
                if (!temp_row_in_blocks.empty()) {
506
                    // no more rows to merge for prev row, finalize it
507
639k
                    _finalize_one_row<is_final>(temp_row_in_blocks.back(), block_data, row_pos);
508
639k
                }
509
643k
                temp_row_in_blocks.push_back(prev_row);
510
643k
                row_pos++;
511
643k
            }
512
841k
        }
513
4.15k
        if (!temp_row_in_blocks.empty()) {
514
            // finalize the last low
515
4.15k
            _finalize_one_row<is_final>(temp_row_in_blocks.back(), block_data, row_pos);
516
4.15k
        }
517
4.15k
    } 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
32
        RowInBlock* row_with_seq_col = nullptr;
527
32
        int row_pos_with_seq = -1;
528
32
        RowInBlock* row_without_seq_col = nullptr;
529
32
        int row_pos_without_seq = -1;
530
531
160
        auto finalize_rows = [&]() {
532
160
            if (row_with_seq_col != nullptr) {
533
128
                _finalize_one_row<is_final>(row_with_seq_col, block_data, row_pos_with_seq);
534
128
                row_with_seq_col = nullptr;
535
128
            }
536
160
            if (row_without_seq_col != nullptr) {
537
128
                _finalize_one_row<is_final>(row_without_seq_col, block_data, row_pos_without_seq);
538
128
                row_without_seq_col = nullptr;
539
128
            }
540
160
        };
Unexecuted instantiation: _ZZN5doris8MemTable10_aggregateILb0ELb1EEEvvENKUlvE_clEv
_ZZN5doris8MemTable10_aggregateILb1ELb1EEEvvENKUlvE_clEv
Line
Count
Source
531
160
        auto finalize_rows = [&]() {
532
160
            if (row_with_seq_col != nullptr) {
533
128
                _finalize_one_row<is_final>(row_with_seq_col, block_data, row_pos_with_seq);
534
128
                row_with_seq_col = nullptr;
535
128
            }
536
160
            if (row_without_seq_col != nullptr) {
537
128
                _finalize_one_row<is_final>(row_without_seq_col, block_data, row_pos_without_seq);
538
128
                row_without_seq_col = nullptr;
539
128
            }
540
160
        };
541
256
        auto add_row = [&](RowInBlock* row, bool with_seq_col) {
542
256
            temp_row_in_blocks.push_back(row);
543
256
            row_pos++;
544
256
            if (with_seq_col) {
545
128
                row_with_seq_col = row;
546
128
                row_pos_with_seq = row_pos;
547
128
            } else {
548
128
                row_without_seq_col = row;
549
128
                row_pos_without_seq = row_pos;
550
128
            }
551
256
        };
Unexecuted instantiation: _ZZN5doris8MemTable10_aggregateILb0ELb1EEEvvENKUlPNS_10RowInBlockEbE_clES3_b
_ZZN5doris8MemTable10_aggregateILb1ELb1EEEvvENKUlPNS_10RowInBlockEbE_clES3_b
Line
Count
Source
541
256
        auto add_row = [&](RowInBlock* row, bool with_seq_col) {
542
256
            temp_row_in_blocks.push_back(row);
543
256
            row_pos++;
544
256
            if (with_seq_col) {
545
128
                row_with_seq_col = row;
546
128
                row_pos_with_seq = row_pos;
547
128
            } else {
548
128
                row_without_seq_col = row;
549
128
                row_pos_without_seq = row_pos;
550
128
            }
551
256
        };
552
32
        auto& skip_bitmaps = assert_cast<vectorized::ColumnBitmap*>(
553
32
                                     mutable_block.mutable_columns()[_skip_bitmap_col_idx].get())
554
32
                                     ->get_data();
555
568
        for (auto* cur_row : *_row_in_blocks) {
556
568
            const BitmapValue& skip_bitmap = skip_bitmaps[cur_row->_row_pos];
557
568
            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
568
            prev_row = (row_with_seq_col == nullptr) ? row_without_seq_col : row_with_seq_col;
561
568
            if (prev_row != nullptr && (*_vec_row_comparator)(prev_row, cur_row) == 0) {
562
440
                prev_row = (with_seq_col ? row_with_seq_col : row_without_seq_col);
563
440
                if (prev_row == nullptr) {
564
128
                    add_row(cur_row, with_seq_col);
565
128
                    continue;
566
128
                }
567
312
                if (!prev_row->has_init_agg()) {
568
144
                    init_for_agg(prev_row);
569
144
                }
570
312
                _stat.merged_rows++;
571
312
                _aggregate_two_row_in_block<has_skip_bitmap_col>(mutable_block, cur_row, prev_row);
572
312
            } else {
573
                // no more rows to merge for prev rows, finalize them
574
128
                finalize_rows();
575
128
                add_row(cur_row, with_seq_col);
576
128
            }
577
568
        }
578
        // finalize the last lows
579
32
        finalize_rows();
580
32
    }
581
4.18k
    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
4.18k
}
Unexecuted instantiation: _ZN5doris8MemTable10_aggregateILb0ELb0EEEvv
Unexecuted instantiation: _ZN5doris8MemTable10_aggregateILb0ELb1EEEvv
_ZN5doris8MemTable10_aggregateILb1ELb0EEEvv
Line
Count
Source
469
3.83k
void MemTable::_aggregate() {
470
3.83k
    SCOPED_RAW_TIMER(&_stat.agg_ns);
471
3.83k
    _stat.agg_times++;
472
3.83k
    vectorized::Block in_block = _input_mutable_block.to_block();
473
3.83k
    vectorized::MutableBlock mutable_block =
474
3.83k
            vectorized::MutableBlock::build_mutable_block(&in_block);
475
3.83k
    _vec_row_comparator->set_block(&mutable_block);
476
3.83k
    auto& block_data = in_block.get_columns_with_type_and_name();
477
3.83k
    DorisVector<RowInBlock*> temp_row_in_blocks;
478
3.83k
    temp_row_in_blocks.reserve(_last_sorted_pos);
479
3.83k
    RowInBlock* prev_row = nullptr;
480
3.83k
    int row_pos = -1;
481
    //only init agg if needed
482
483
3.83k
    auto init_for_agg = [&](RowInBlock* row) {
484
3.83k
        row->init_agg_places(_arena->aligned_alloc(_total_size_of_aggregate_states, 16),
485
3.83k
                             _offsets_of_aggregate_states.data());
486
3.83k
        for (auto cid = _tablet_schema->num_key_columns(); cid < _num_columns; cid++) {
487
3.83k
            auto* col_ptr = mutable_block.mutable_columns()[cid].get();
488
3.83k
            auto* data = prev_row->agg_places(cid);
489
3.83k
            _agg_functions[cid]->create(data);
490
3.83k
            _agg_functions[cid]->add(data, const_cast<const doris::vectorized::IColumn**>(&col_ptr),
491
3.83k
                                     prev_row->_row_pos, _arena.get());
492
3.83k
        }
493
3.83k
    };
494
495
3.83k
    if (!has_skip_bitmap_col || _seq_col_idx_in_block == -1) {
496
830k
        for (RowInBlock* cur_row : *_row_in_blocks) {
497
830k
            if (!temp_row_in_blocks.empty() && (*_vec_row_comparator)(prev_row, cur_row) == 0) {
498
190k
                if (!prev_row->has_init_agg()) {
499
13.6k
                    init_for_agg(prev_row);
500
13.6k
                }
501
190k
                _stat.merged_rows++;
502
190k
                _aggregate_two_row_in_block<has_skip_bitmap_col>(mutable_block, cur_row, prev_row);
503
639k
            } else {
504
639k
                prev_row = cur_row;
505
639k
                if (!temp_row_in_blocks.empty()) {
506
                    // no more rows to merge for prev row, finalize it
507
636k
                    _finalize_one_row<is_final>(temp_row_in_blocks.back(), block_data, row_pos);
508
636k
                }
509
639k
                temp_row_in_blocks.push_back(prev_row);
510
639k
                row_pos++;
511
639k
            }
512
830k
        }
513
3.83k
        if (!temp_row_in_blocks.empty()) {
514
            // finalize the last low
515
3.83k
            _finalize_one_row<is_final>(temp_row_in_blocks.back(), block_data, row_pos);
516
3.83k
        }
517
3.83k
    } 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
3.83k
    if constexpr (!is_final) {
582
        // if is not final, we collect the agg results to input_block and then continue to insert
583
3.83k
        _input_mutable_block.swap(_output_mutable_block);
584
        //TODO(weixang):opt here.
585
3.83k
        std::unique_ptr<vectorized::Block> empty_input_block = in_block.create_same_struct_block(0);
586
3.83k
        _output_mutable_block =
587
3.83k
                vectorized::MutableBlock::build_mutable_block(empty_input_block.get());
588
3.83k
        _output_mutable_block.clear_column_data();
589
3.83k
        *_row_in_blocks = temp_row_in_blocks;
590
3.83k
        _last_sorted_pos = _row_in_blocks->size();
591
3.83k
    }
592
3.83k
}
_ZN5doris8MemTable10_aggregateILb1ELb1EEEvv
Line
Count
Source
469
348
void MemTable::_aggregate() {
470
348
    SCOPED_RAW_TIMER(&_stat.agg_ns);
471
348
    _stat.agg_times++;
472
348
    vectorized::Block in_block = _input_mutable_block.to_block();
473
348
    vectorized::MutableBlock mutable_block =
474
348
            vectorized::MutableBlock::build_mutable_block(&in_block);
475
348
    _vec_row_comparator->set_block(&mutable_block);
476
348
    auto& block_data = in_block.get_columns_with_type_and_name();
477
348
    DorisVector<RowInBlock*> temp_row_in_blocks;
478
348
    temp_row_in_blocks.reserve(_last_sorted_pos);
479
348
    RowInBlock* prev_row = nullptr;
480
348
    int row_pos = -1;
481
    //only init agg if needed
482
483
348
    auto init_for_agg = [&](RowInBlock* row) {
484
348
        row->init_agg_places(_arena->aligned_alloc(_total_size_of_aggregate_states, 16),
485
348
                             _offsets_of_aggregate_states.data());
486
348
        for (auto cid = _tablet_schema->num_key_columns(); cid < _num_columns; cid++) {
487
348
            auto* col_ptr = mutable_block.mutable_columns()[cid].get();
488
348
            auto* data = prev_row->agg_places(cid);
489
348
            _agg_functions[cid]->create(data);
490
348
            _agg_functions[cid]->add(data, const_cast<const doris::vectorized::IColumn**>(&col_ptr),
491
348
                                     prev_row->_row_pos, _arena.get());
492
348
        }
493
348
    };
494
495
348
    if (!has_skip_bitmap_col || _seq_col_idx_in_block == -1) {
496
11.3k
        for (RowInBlock* cur_row : *_row_in_blocks) {
497
11.3k
            if (!temp_row_in_blocks.empty() && (*_vec_row_comparator)(prev_row, cur_row) == 0) {
498
7.88k
                if (!prev_row->has_init_agg()) {
499
2.86k
                    init_for_agg(prev_row);
500
2.86k
                }
501
7.88k
                _stat.merged_rows++;
502
7.88k
                _aggregate_two_row_in_block<has_skip_bitmap_col>(mutable_block, cur_row, prev_row);
503
7.88k
            } else {
504
3.48k
                prev_row = cur_row;
505
3.48k
                if (!temp_row_in_blocks.empty()) {
506
                    // no more rows to merge for prev row, finalize it
507
3.17k
                    _finalize_one_row<is_final>(temp_row_in_blocks.back(), block_data, row_pos);
508
3.17k
                }
509
3.48k
                temp_row_in_blocks.push_back(prev_row);
510
3.48k
                row_pos++;
511
3.48k
            }
512
11.3k
        }
513
316
        if (!temp_row_in_blocks.empty()) {
514
            // finalize the last low
515
316
            _finalize_one_row<is_final>(temp_row_in_blocks.back(), block_data, row_pos);
516
316
        }
517
316
    } 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
32
        RowInBlock* row_with_seq_col = nullptr;
527
32
        int row_pos_with_seq = -1;
528
32
        RowInBlock* row_without_seq_col = nullptr;
529
32
        int row_pos_without_seq = -1;
530
531
32
        auto finalize_rows = [&]() {
532
32
            if (row_with_seq_col != nullptr) {
533
32
                _finalize_one_row<is_final>(row_with_seq_col, block_data, row_pos_with_seq);
534
32
                row_with_seq_col = nullptr;
535
32
            }
536
32
            if (row_without_seq_col != nullptr) {
537
32
                _finalize_one_row<is_final>(row_without_seq_col, block_data, row_pos_without_seq);
538
32
                row_without_seq_col = nullptr;
539
32
            }
540
32
        };
541
32
        auto add_row = [&](RowInBlock* row, bool with_seq_col) {
542
32
            temp_row_in_blocks.push_back(row);
543
32
            row_pos++;
544
32
            if (with_seq_col) {
545
32
                row_with_seq_col = row;
546
32
                row_pos_with_seq = row_pos;
547
32
            } else {
548
32
                row_without_seq_col = row;
549
32
                row_pos_without_seq = row_pos;
550
32
            }
551
32
        };
552
32
        auto& skip_bitmaps = assert_cast<vectorized::ColumnBitmap*>(
553
32
                                     mutable_block.mutable_columns()[_skip_bitmap_col_idx].get())
554
32
                                     ->get_data();
555
568
        for (auto* cur_row : *_row_in_blocks) {
556
568
            const BitmapValue& skip_bitmap = skip_bitmaps[cur_row->_row_pos];
557
568
            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
568
            prev_row = (row_with_seq_col == nullptr) ? row_without_seq_col : row_with_seq_col;
561
568
            if (prev_row != nullptr && (*_vec_row_comparator)(prev_row, cur_row) == 0) {
562
440
                prev_row = (with_seq_col ? row_with_seq_col : row_without_seq_col);
563
440
                if (prev_row == nullptr) {
564
128
                    add_row(cur_row, with_seq_col);
565
128
                    continue;
566
128
                }
567
312
                if (!prev_row->has_init_agg()) {
568
144
                    init_for_agg(prev_row);
569
144
                }
570
312
                _stat.merged_rows++;
571
312
                _aggregate_two_row_in_block<has_skip_bitmap_col>(mutable_block, cur_row, prev_row);
572
312
            } else {
573
                // no more rows to merge for prev rows, finalize them
574
128
                finalize_rows();
575
128
                add_row(cur_row, with_seq_col);
576
128
            }
577
568
        }
578
        // finalize the last lows
579
32
        finalize_rows();
580
32
    }
581
348
    if constexpr (!is_final) {
582
        // if is not final, we collect the agg results to input_block and then continue to insert
583
348
        _input_mutable_block.swap(_output_mutable_block);
584
        //TODO(weixang):opt here.
585
348
        std::unique_ptr<vectorized::Block> empty_input_block = in_block.create_same_struct_block(0);
586
348
        _output_mutable_block =
587
348
                vectorized::MutableBlock::build_mutable_block(empty_input_block.get());
588
348
        _output_mutable_block.clear_column_data();
589
348
        *_row_in_blocks = temp_row_in_blocks;
590
348
        _last_sorted_pos = _row_in_blocks->size();
591
348
    }
592
348
}
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
273k
bool MemTable::need_flush() const {
608
273k
    DBUG_EXECUTE_IF("MemTable.need_flush", { return true; });
609
273k
    auto max_size = config::write_buffer_size;
610
273k
    if (_partial_update_mode == UniqueKeyUpdateModePB::UPDATE_FIXED_COLUMNS) {
611
2.01k
        auto update_columns_size = _num_columns;
612
2.01k
        max_size = max_size * update_columns_size / _tablet_schema->num_columns();
613
2.01k
        max_size = max_size > 1048576 ? max_size : 1048576;
614
2.01k
    }
615
273k
    return memory_usage() >= max_size;
616
273k
}
617
618
273k
bool MemTable::need_agg() const {
619
273k
    if (_keys_type == KeysType::AGG_KEYS) {
620
9.18k
        auto max_size = config::write_buffer_size_for_agg;
621
9.18k
        return memory_usage() >= max_size;
622
9.18k
    }
623
264k
    return false;
624
273k
}
625
626
121k
size_t MemTable::get_flush_reserve_memory_size() const {
627
121k
    if (_keys_type == KeysType::DUP_KEYS && _tablet_schema->num_key_columns() == 0) {
628
46
        return 0; // no need to reserve
629
46
    }
630
121k
    return static_cast<size_t>(static_cast<double>(_input_mutable_block.allocated_bytes()) * 1.2);
631
121k
}
632
633
121k
Status MemTable::_to_block(std::unique_ptr<vectorized::Block>* res) {
634
121k
    size_t same_keys_num = _sort();
635
121k
    if (_keys_type == KeysType::DUP_KEYS || same_keys_num == 0) {
636
117k
        if (_keys_type == KeysType::DUP_KEYS && _tablet_schema->num_key_columns() == 0) {
637
46
            _output_mutable_block.swap(_input_mutable_block);
638
117k
        } else {
639
117k
            vectorized::Block in_block = _input_mutable_block.to_block();
640
117k
            RETURN_IF_ERROR(_put_into_output(in_block));
641
117k
        }
642
117k
    } else {
643
4.18k
        (_skip_bitmap_col_idx == -1) ? _aggregate<true, false>() : _aggregate<true, true>();
644
4.18k
    }
645
121k
    if (_keys_type == KeysType::UNIQUE_KEYS && _enable_unique_key_mow &&
646
121k
        !_tablet_schema->cluster_key_uids().empty()) {
647
3.10k
        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
3.10k
        RETURN_IF_ERROR(_sort_by_cluster_keys());
652
3.10k
    }
653
121k
    _input_mutable_block.clear();
654
121k
    *res = vectorized::Block::create_unique(_output_mutable_block.to_block());
655
121k
    return Status::OK();
656
121k
}
657
658
121k
Status MemTable::to_block(std::unique_ptr<vectorized::Block>* res) {
659
121k
    RETURN_IF_ERROR_OR_CATCH_EXCEPTION(_to_block(res));
660
121k
    return Status::OK();
661
121k
}
662
663
#include "common/compile_check_end.h"
664
} // namespace doris