Coverage Report

Created: 2025-06-16 18:22

/root/doris/be/src/olap/memtable.cpp
Line
Count
Source (jump to first uncovered line)
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "olap/memtable.h"
19
20
#include <fmt/format.h>
21
#include <gen_cpp/olap_file.pb.h>
22
#include <pdqsort.h>
23
24
#include <algorithm>
25
#include <limits>
26
#include <string>
27
#include <vector>
28
29
#include "bvar/bvar.h"
30
#include "common/config.h"
31
#include "olap/memtable_memory_limiter.h"
32
#include "olap/olap_define.h"
33
#include "olap/tablet_schema.h"
34
#include "runtime/descriptors.h"
35
#include "runtime/exec_env.h"
36
#include "runtime/thread_context.h"
37
#include "util/debug_points.h"
38
#include "util/runtime_profile.h"
39
#include "util/stopwatch.hpp"
40
#include "vec/aggregate_functions/aggregate_function_reader.h"
41
#include "vec/aggregate_functions/aggregate_function_simple_factory.h"
42
#include "vec/columns/column.h"
43
44
namespace doris {
45
#include "common/compile_check_begin.h"
46
47
bvar::Adder<int64_t> g_memtable_cnt("memtable_cnt");
48
49
using namespace ErrorCode;
50
51
MemTable::MemTable(int64_t tablet_id, std::shared_ptr<TabletSchema> tablet_schema,
52
                   const std::vector<SlotDescriptor*>* slot_descs, TupleDescriptor* tuple_desc,
53
                   bool enable_unique_key_mow, PartialUpdateInfo* partial_update_info,
54
                   const std::shared_ptr<ResourceContext>& resource_ctx)
55
        : _mem_type(MemType::ACTIVE),
56
          _tablet_id(tablet_id),
57
          _enable_unique_key_mow(enable_unique_key_mow),
58
          _keys_type(tablet_schema->keys_type()),
59
          _tablet_schema(tablet_schema),
60
          _resource_ctx(resource_ctx),
61
          _is_first_insertion(true),
62
          _agg_functions(tablet_schema->num_columns()),
63
          _offsets_of_aggregate_states(tablet_schema->num_columns()),
64
169k
          _total_size_of_aggregate_states(0) {
65
169k
    g_memtable_cnt << 1;
66
169k
    _mem_tracker = std::make_shared<MemTracker>();
67
169k
    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(
68
169k
            _resource_ctx->memory_context()->mem_tracker()->write_tracker());
69
169k
    SCOPED_CONSUME_MEM_TRACKER(_mem_tracker);
70
169k
    _arena = std::make_unique<vectorized::Arena>();
71
169k
    _vec_row_comparator = std::make_shared<RowInBlockComparator>(_tablet_schema);
72
169k
    _num_columns = _tablet_schema->num_columns();
73
169k
    if (partial_update_info != nullptr) {
74
169k
        _partial_update_mode = partial_update_info->update_mode();
75
169k
        if (_partial_update_mode == UniqueKeyUpdateModePB::UPDATE_FIXED_COLUMNS) {
76
4.90k
            _num_columns = partial_update_info->partial_update_input_columns.size();
77
4.90k
            if (partial_update_info->is_schema_contains_auto_inc_column &&
78
4.90k
                !partial_update_info->is_input_columns_contains_auto_inc_column) {
79
386
                _is_partial_update_and_auto_inc = true;
80
386
                _num_columns += 1;
81
386
            }
82
4.90k
        }
83
169k
    }
84
    // TODO: Support ZOrderComparator in the future
85
169k
    _init_columns_offset_by_slot_descs(slot_descs, tuple_desc);
86
169k
    _row_in_blocks = std::make_unique<DorisVector<RowInBlock*>>();
87
169k
}
88
89
void MemTable::_init_columns_offset_by_slot_descs(const std::vector<SlotDescriptor*>* slot_descs,
90
169k
                                                  const TupleDescriptor* tuple_desc) {
91
2.35M
    for (auto slot_desc : *slot_descs) {
92
2.35M
        const auto& slots = tuple_desc->slots();
93
34.7M
        for (int j = 0; j < slots.size(); ++j) {
94
34.7M
            if (slot_desc->id() == slots[j]->id()) {
95
2.35M
                _column_offset.emplace_back(j);
96
2.35M
                break;
97
2.35M
            }
98
34.7M
        }
99
2.35M
    }
100
169k
    if (_is_partial_update_and_auto_inc) {
101
386
        _column_offset.emplace_back(_column_offset.size());
102
386
    }
103
169k
}
104
105
59.2k
void MemTable::_init_agg_functions(const vectorized::Block* block) {
106
706k
    for (auto cid = _tablet_schema->num_key_columns(); cid < _num_columns; ++cid) {
107
647k
        vectorized::AggregateFunctionPtr function;
108
647k
        if (_keys_type == KeysType::UNIQUE_KEYS && _enable_unique_key_mow) {
109
            // In such table, non-key column's aggregation type is NONE, so we need to construct
110
            // the aggregate function manually.
111
550k
            if (_skip_bitmap_col_idx != cid) {
112
550k
                function = vectorized::AggregateFunctionSimpleFactory::instance().get(
113
550k
                        "replace_load", {block->get_data_type(cid)},
114
550k
                        block->get_data_type(cid)->is_nullable(),
115
550k
                        BeExecVersionManager::get_newest_version());
116
550k
            } else {
117
554
                function = vectorized::AggregateFunctionSimpleFactory::instance().get(
118
554
                        "bitmap_intersect", {block->get_data_type(cid)}, false,
119
554
                        BeExecVersionManager::get_newest_version());
120
554
            }
121
550k
        } else {
122
96.5k
            function = _tablet_schema->column(cid).get_aggregate_function(
123
96.5k
                    vectorized::AGG_LOAD_SUFFIX, _tablet_schema->column(cid).get_be_exec_version());
124
96.5k
            if (function == nullptr) {
125
0
                LOG(WARNING) << "column get aggregate function failed, column="
126
0
                             << _tablet_schema->column(cid).name();
127
0
            }
128
96.5k
        }
129
130
647k
        DCHECK(function != nullptr);
131
647k
        _agg_functions[cid] = function;
132
647k
    }
133
134
706k
    for (auto cid = _tablet_schema->num_key_columns(); cid < _num_columns; ++cid) {
135
647k
        _offsets_of_aggregate_states[cid] = _total_size_of_aggregate_states;
136
647k
        _total_size_of_aggregate_states += _agg_functions[cid]->size_of_data();
137
138
        // If not the last aggregate_state, we need pad it so that next aggregate_state will be aligned.
139
647k
        if (cid + 1 < _num_columns) {
140
588k
            size_t alignment_of_next_state = _agg_functions[cid + 1]->align_of_data();
141
142
            /// Extend total_size to next alignment requirement
143
            /// Add padding by rounding up 'total_size_of_aggregate_states' to be a multiplier of alignment_of_next_state.
144
588k
            _total_size_of_aggregate_states =
145
588k
                    (_total_size_of_aggregate_states + alignment_of_next_state - 1) /
146
588k
                    alignment_of_next_state * alignment_of_next_state;
147
588k
        }
148
647k
    }
149
59.2k
}
150
151
169k
MemTable::~MemTable() {
152
169k
    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(
153
169k
            _resource_ctx->memory_context()->mem_tracker()->write_tracker());
154
169k
    {
155
169k
        SCOPED_CONSUME_MEM_TRACKER(_mem_tracker);
156
169k
        g_memtable_cnt << -1;
157
169k
        if (_keys_type != KeysType::DUP_KEYS) {
158
28.2M
            for (auto it = _row_in_blocks->begin(); it != _row_in_blocks->end(); it++) {
159
28.2M
                if (!(*it)->has_init_agg()) {
160
28.2M
                    continue;
161
28.2M
                }
162
                // We should release agg_places here, because they are not released when a
163
                // load is canceled.
164
18.4E
                for (size_t i = _tablet_schema->num_key_columns(); i < _num_columns; ++i) {
165
0
                    auto function = _agg_functions[i];
166
0
                    DCHECK(function != nullptr);
167
0
                    function->destroy((*it)->agg_places(i));
168
0
                }
169
18.4E
            }
170
86.4k
        }
171
172
169k
        std::for_each(_row_in_blocks->begin(), _row_in_blocks->end(),
173
169k
                      std::default_delete<RowInBlock>());
174
        // Arena has to be destroyed after agg state, because some agg state's memory may be
175
        // allocated in arena.
176
169k
        _arena.reset();
177
169k
        _vec_row_comparator.reset();
178
169k
        _row_in_blocks.reset();
179
169k
        _agg_functions.clear();
180
169k
        _input_mutable_block.clear();
181
169k
        _output_mutable_block.clear();
182
169k
    }
183
169k
    if (_is_flush_success) {
184
        // If the memtable is flush success, then its memtracker's consumption should be 0
185
127k
        if (_mem_tracker->consumption() != 0 && config::crash_in_memory_tracker_inaccurate) {
186
0
            LOG(FATAL) << "memtable flush success but cosumption is not 0, it is "
187
0
                       << _mem_tracker->consumption();
188
0
        }
189
127k
    }
190
169k
}
191
192
825k
int RowInBlockComparator::operator()(const RowInBlock* left, const RowInBlock* right) const {
193
825k
    return _pblock->compare_at(left->_row_pos, right->_row_pos, _tablet_schema->num_key_columns(),
194
825k
                               *_pblock, -1);
195
825k
}
196
197
Status MemTable::insert(const vectorized::Block* input_block,
198
279k
                        const DorisVector<uint32_t>& row_idxs) {
199
279k
    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(
200
279k
            _resource_ctx->memory_context()->mem_tracker()->write_tracker());
201
279k
    SCOPED_CONSUME_MEM_TRACKER(_mem_tracker);
202
203
279k
    if (_is_first_insertion) {
204
127k
        _is_first_insertion = false;
205
127k
        auto clone_block = input_block->clone_without_columns(&_column_offset);
206
127k
        _input_mutable_block = vectorized::MutableBlock::build_mutable_block(&clone_block);
207
127k
        _vec_row_comparator->set_block(&_input_mutable_block);
208
127k
        _output_mutable_block = vectorized::MutableBlock::build_mutable_block(&clone_block);
209
127k
        if (_tablet_schema->has_sequence_col()) {
210
2.36k
            if (_partial_update_mode == UniqueKeyUpdateModePB::UPDATE_FIXED_COLUMNS) {
211
                // for unique key fixed partial update, sequence column index in block
212
                // may be different with the index in `_tablet_schema`
213
1.02k
                for (int32_t i = 0; i < clone_block.columns(); i++) {
214
822
                    if (clone_block.get_by_position(i).name == SEQUENCE_COL) {
215
76
                        _seq_col_idx_in_block = i;
216
76
                        break;
217
76
                    }
218
822
                }
219
2.08k
            } else {
220
2.08k
                _seq_col_idx_in_block = _tablet_schema->sequence_col_idx();
221
2.08k
            }
222
2.36k
        }
223
127k
        if (_partial_update_mode == UniqueKeyUpdateModePB::UPDATE_FLEXIBLE_COLUMNS &&
224
127k
            _tablet_schema->has_skip_bitmap_col()) {
225
            // init of _skip_bitmap_col_idx must be before _init_agg_functions()
226
556
            _skip_bitmap_col_idx = _tablet_schema->skip_bitmap_col_idx();
227
556
            if (_seq_col_idx_in_block != -1) {
228
48
                _seq_col_unique_id = _tablet_schema->column(_seq_col_idx_in_block).unique_id();
229
48
            }
230
556
        }
231
127k
        if (_keys_type != KeysType::DUP_KEYS) {
232
            // there may be additional intermediate columns in input_block
233
            // we only need columns indicated by column offset in the output
234
59.2k
            RETURN_IF_CATCH_EXCEPTION(_init_agg_functions(&clone_block));
235
59.2k
        }
236
127k
    }
237
238
279k
    auto num_rows = row_idxs.size();
239
279k
    size_t cursor_in_mutableblock = _input_mutable_block.rows();
240
279k
    RETURN_IF_ERROR(_input_mutable_block.add_rows(input_block, row_idxs.data(),
241
279k
                                                  row_idxs.data() + num_rows, &_column_offset));
242
96.3M
    for (int i = 0; i < num_rows; i++) {
243
96.0M
        _row_in_blocks->emplace_back(new RowInBlock {cursor_in_mutableblock + i});
244
96.0M
    }
245
246
279k
    _stat.raw_rows += num_rows;
247
279k
    return Status::OK();
248
279k
}
249
250
template <bool has_skip_bitmap_col>
251
void MemTable::_aggregate_two_row_in_block(vectorized::MutableBlock& mutable_block,
252
186k
                                           RowInBlock* src_row, RowInBlock* dst_row) {
253
    // for flexible partial update, the caller must guarantees that either src_row and dst_row
254
    // both specify the sequence column, or src_row and dst_row both don't specify the
255
    // sequence column
256
186k
    if (_tablet_schema->has_sequence_col() && _seq_col_idx_in_block >= 0) {
257
649
        DCHECK_LT(_seq_col_idx_in_block, mutable_block.columns());
258
649
        auto col_ptr = mutable_block.mutable_columns()[_seq_col_idx_in_block].get();
259
649
        auto res = col_ptr->compare_at(dst_row->_row_pos, src_row->_row_pos, *col_ptr, -1);
260
        // dst sequence column larger than src, don't need to update
261
649
        if (res > 0) {
262
209
            return;
263
209
        }
264
        // need to update the row pos in dst row to the src row pos when has
265
        // sequence column
266
440
        dst_row->_row_pos = src_row->_row_pos;
267
440
    }
268
    // dst is non-sequence row, or dst sequence is smaller
269
186k
    if constexpr (!has_skip_bitmap_col) {
270
8.14k
        DCHECK(_skip_bitmap_col_idx == -1);
271
751k
        for (size_t cid = _tablet_schema->num_key_columns(); cid < _num_columns; ++cid) {
272
573k
            auto* col_ptr = mutable_block.mutable_columns()[cid].get();
273
573k
            _agg_functions[cid]->add(dst_row->agg_places(cid),
274
573k
                                     const_cast<const doris::vectorized::IColumn**>(&col_ptr),
275
573k
                                     src_row->_row_pos, _arena.get());
276
573k
        }
277
177k
    } else {
278
8.14k
        DCHECK(_skip_bitmap_col_idx != -1);
279
8.14k
        DCHECK_LT(_skip_bitmap_col_idx, mutable_block.columns());
280
8.14k
        const BitmapValue& skip_bitmap =
281
8.14k
                assert_cast<vectorized::ColumnBitmap*, TypeCheckOnRelease::DISABLE>(
282
8.14k
                        mutable_block.mutable_columns()[_skip_bitmap_col_idx].get())
283
8.14k
                        ->get_data()[src_row->_row_pos];
284
143k
        for (size_t cid = _tablet_schema->num_key_columns(); cid < _num_columns; ++cid) {
285
135k
            const auto& col = _tablet_schema->column(cid);
286
135k
            if (cid != _skip_bitmap_col_idx && skip_bitmap.contains(col.unique_id())) {
287
68.3k
                continue;
288
68.3k
            }
289
67.3k
            auto* col_ptr = mutable_block.mutable_columns()[cid].get();
290
67.3k
            _agg_functions[cid]->add(dst_row->agg_places(cid),
291
67.3k
                                     const_cast<const doris::vectorized::IColumn**>(&col_ptr),
292
67.3k
                                     src_row->_row_pos, _arena.get());
293
67.3k
        }
294
8.14k
    }
295
186k
}
_ZN5doris8MemTable27_aggregate_two_row_in_blockILb0EEEvRNS_10vectorized12MutableBlockEPNS_10RowInBlockES6_
Line
Count
Source
252
178k
                                           RowInBlock* src_row, RowInBlock* dst_row) {
253
    // for flexible partial update, the caller must guarantees that either src_row and dst_row
254
    // both specify the sequence column, or src_row and dst_row both don't specify the
255
    // sequence column
256
178k
    if (_tablet_schema->has_sequence_col() && _seq_col_idx_in_block >= 0) {
257
337
        DCHECK_LT(_seq_col_idx_in_block, mutable_block.columns());
258
337
        auto col_ptr = mutable_block.mutable_columns()[_seq_col_idx_in_block].get();
259
337
        auto res = col_ptr->compare_at(dst_row->_row_pos, src_row->_row_pos, *col_ptr, -1);
260
        // dst sequence column larger than src, don't need to update
261
337
        if (res > 0) {
262
173
            return;
263
173
        }
264
        // need to update the row pos in dst row to the src row pos when has
265
        // sequence column
266
164
        dst_row->_row_pos = src_row->_row_pos;
267
164
    }
268
    // dst is non-sequence row, or dst sequence is smaller
269
178k
    if constexpr (!has_skip_bitmap_col) {
270
177k
        DCHECK(_skip_bitmap_col_idx == -1);
271
751k
        for (size_t cid = _tablet_schema->num_key_columns(); cid < _num_columns; ++cid) {
272
573k
            auto* col_ptr = mutable_block.mutable_columns()[cid].get();
273
573k
            _agg_functions[cid]->add(dst_row->agg_places(cid),
274
573k
                                     const_cast<const doris::vectorized::IColumn**>(&col_ptr),
275
573k
                                     src_row->_row_pos, _arena.get());
276
573k
        }
277
177k
    } else {
278
178k
        DCHECK(_skip_bitmap_col_idx != -1);
279
178k
        DCHECK_LT(_skip_bitmap_col_idx, mutable_block.columns());
280
178k
        const BitmapValue& skip_bitmap =
281
178k
                assert_cast<vectorized::ColumnBitmap*, TypeCheckOnRelease::DISABLE>(
282
178k
                        mutable_block.mutable_columns()[_skip_bitmap_col_idx].get())
283
178k
                        ->get_data()[src_row->_row_pos];
284
178k
        for (size_t cid = _tablet_schema->num_key_columns(); cid < _num_columns; ++cid) {
285
178k
            const auto& col = _tablet_schema->column(cid);
286
178k
            if (cid != _skip_bitmap_col_idx && skip_bitmap.contains(col.unique_id())) {
287
178k
                continue;
288
178k
            }
289
178k
            auto* col_ptr = mutable_block.mutable_columns()[cid].get();
290
178k
            _agg_functions[cid]->add(dst_row->agg_places(cid),
291
178k
                                     const_cast<const doris::vectorized::IColumn**>(&col_ptr),
292
178k
                                     src_row->_row_pos, _arena.get());
293
178k
        }
294
178k
    }
295
178k
}
_ZN5doris8MemTable27_aggregate_two_row_in_blockILb1EEEvRNS_10vectorized12MutableBlockEPNS_10RowInBlockES6_
Line
Count
Source
252
8.18k
                                           RowInBlock* src_row, RowInBlock* dst_row) {
253
    // for flexible partial update, the caller must guarantees that either src_row and dst_row
254
    // both specify the sequence column, or src_row and dst_row both don't specify the
255
    // sequence column
256
8.18k
    if (_tablet_schema->has_sequence_col() && _seq_col_idx_in_block >= 0) {
257
312
        DCHECK_LT(_seq_col_idx_in_block, mutable_block.columns());
258
312
        auto col_ptr = mutable_block.mutable_columns()[_seq_col_idx_in_block].get();
259
312
        auto res = col_ptr->compare_at(dst_row->_row_pos, src_row->_row_pos, *col_ptr, -1);
260
        // dst sequence column larger than src, don't need to update
261
312
        if (res > 0) {
262
36
            return;
263
36
        }
264
        // need to update the row pos in dst row to the src row pos when has
265
        // sequence column
266
276
        dst_row->_row_pos = src_row->_row_pos;
267
276
    }
268
    // dst is non-sequence row, or dst sequence is smaller
269
8.14k
    if constexpr (!has_skip_bitmap_col) {
270
8.14k
        DCHECK(_skip_bitmap_col_idx == -1);
271
8.14k
        for (size_t cid = _tablet_schema->num_key_columns(); cid < _num_columns; ++cid) {
272
8.14k
            auto* col_ptr = mutable_block.mutable_columns()[cid].get();
273
8.14k
            _agg_functions[cid]->add(dst_row->agg_places(cid),
274
8.14k
                                     const_cast<const doris::vectorized::IColumn**>(&col_ptr),
275
8.14k
                                     src_row->_row_pos, _arena.get());
276
8.14k
        }
277
8.14k
    } else {
278
8.14k
        DCHECK(_skip_bitmap_col_idx != -1);
279
8.14k
        DCHECK_LT(_skip_bitmap_col_idx, mutable_block.columns());
280
8.14k
        const BitmapValue& skip_bitmap =
281
8.14k
                assert_cast<vectorized::ColumnBitmap*, TypeCheckOnRelease::DISABLE>(
282
8.14k
                        mutable_block.mutable_columns()[_skip_bitmap_col_idx].get())
283
8.14k
                        ->get_data()[src_row->_row_pos];
284
143k
        for (size_t cid = _tablet_schema->num_key_columns(); cid < _num_columns; ++cid) {
285
135k
            const auto& col = _tablet_schema->column(cid);
286
135k
            if (cid != _skip_bitmap_col_idx && skip_bitmap.contains(col.unique_id())) {
287
68.3k
                continue;
288
68.3k
            }
289
67.3k
            auto* col_ptr = mutable_block.mutable_columns()[cid].get();
290
67.3k
            _agg_functions[cid]->add(dst_row->agg_places(cid),
291
67.3k
                                     const_cast<const doris::vectorized::IColumn**>(&col_ptr),
292
67.3k
                                     src_row->_row_pos, _arena.get());
293
67.3k
        }
294
8.14k
    }
295
8.14k
}
296
122k
Status MemTable::_put_into_output(vectorized::Block& in_block) {
297
122k
    SCOPED_RAW_TIMER(&_stat.put_into_output_ns);
298
122k
    DorisVector<uint32_t> row_pos_vec;
299
122k
    DCHECK(in_block.rows() <= std::numeric_limits<int>::max());
300
122k
    row_pos_vec.reserve(in_block.rows());
301
92.0M
    for (int i = 0; i < _row_in_blocks->size(); i++) {
302
91.9M
        row_pos_vec.emplace_back((*_row_in_blocks)[i]->_row_pos);
303
91.9M
    }
304
122k
    return _output_mutable_block.add_rows(&in_block, row_pos_vec.data(),
305
122k
                                          row_pos_vec.data() + in_block.rows());
306
122k
}
307
308
127k
size_t MemTable::_sort() {
309
127k
    SCOPED_RAW_TIMER(&_stat.sort_ns);
310
127k
    _stat.sort_times++;
311
127k
    size_t same_keys_num = 0;
312
    // sort new rows
313
127k
    Tie tie = Tie(_last_sorted_pos, _row_in_blocks->size());
314
500k
    for (size_t i = 0; i < _tablet_schema->num_key_columns(); i++) {
315
815M
        auto cmp = [&](const RowInBlock* lhs, const RowInBlock* rhs) -> int {
316
815M
            return _input_mutable_block.compare_one_column(lhs->_row_pos, rhs->_row_pos, i, -1);
317
815M
        };
318
372k
        _sort_one_column(*_row_in_blocks, tie, cmp);
319
372k
    }
320
127k
    bool is_dup = (_keys_type == KeysType::DUP_KEYS);
321
    // sort extra round by _row_pos to make the sort stable
322
127k
    auto iter = tie.iter();
323
508k
    while (iter.next()) {
324
380k
        pdqsort(std::next(_row_in_blocks->begin(), iter.left()),
325
380k
                std::next(_row_in_blocks->begin(), iter.right()),
326
129M
                [&is_dup](const RowInBlock* lhs, const RowInBlock* rhs) -> bool {
327
129M
                    return is_dup ? lhs->_row_pos > rhs->_row_pos : lhs->_row_pos < rhs->_row_pos;
328
129M
                });
329
380k
        same_keys_num += iter.right() - iter.left();
330
380k
    }
331
    // merge new rows and old rows
332
127k
    _vec_row_comparator->set_block(&_input_mutable_block);
333
127k
    auto cmp_func = [this, is_dup, &same_keys_num](const RowInBlock* l,
334
127k
                                                   const RowInBlock* r) -> bool {
335
0
        auto value = (*(this->_vec_row_comparator))(l, r);
336
0
        if (value == 0) {
337
0
            same_keys_num++;
338
0
            return is_dup ? l->_row_pos > r->_row_pos : l->_row_pos < r->_row_pos;
339
0
        } else {
340
0
            return value < 0;
341
0
        }
342
0
    };
343
127k
    auto new_row_it = std::next(_row_in_blocks->begin(), _last_sorted_pos);
344
127k
    std::inplace_merge(_row_in_blocks->begin(), new_row_it, _row_in_blocks->end(), cmp_func);
345
127k
    _last_sorted_pos = _row_in_blocks->size();
346
127k
    return same_keys_num;
347
127k
}
348
349
3.12k
Status MemTable::_sort_by_cluster_keys() {
350
3.12k
    SCOPED_RAW_TIMER(&_stat.sort_ns);
351
3.12k
    _stat.sort_times++;
352
    // sort all rows
353
3.12k
    vectorized::Block in_block = _output_mutable_block.to_block();
354
3.12k
    vectorized::MutableBlock mutable_block =
355
3.12k
            vectorized::MutableBlock::build_mutable_block(&in_block);
356
3.12k
    auto clone_block = in_block.clone_without_columns();
357
3.12k
    _output_mutable_block = vectorized::MutableBlock::build_mutable_block(&clone_block);
358
359
3.12k
    DorisVector<RowInBlock*> row_in_blocks;
360
3.12k
    std::unique_ptr<int, std::function<void(int*)>> row_in_blocks_deleter((int*)0x01, [&](int*) {
361
3.12k
        std::for_each(row_in_blocks.begin(), row_in_blocks.end(),
362
3.12k
                      std::default_delete<RowInBlock>());
363
3.12k
    });
364
3.12k
    row_in_blocks.reserve(mutable_block.rows());
365
1.57M
    for (size_t i = 0; i < mutable_block.rows(); i++) {
366
1.56M
        row_in_blocks.emplace_back(new RowInBlock {i});
367
1.56M
    }
368
3.12k
    Tie tie = Tie(0, mutable_block.rows());
369
370
7.57k
    for (auto cid : _tablet_schema->cluster_key_uids()) {
371
7.57k
        auto index = _tablet_schema->field_index(cid);
372
7.57k
        if (index == -1) {
373
0
            return Status::InternalError("could not find cluster key column with unique_id=" +
374
0
                                         std::to_string(cid) + " in tablet schema");
375
0
        }
376
17.0M
        auto cmp = [&](const RowInBlock* lhs, const RowInBlock* rhs) -> int {
377
17.0M
            return mutable_block.compare_one_column(lhs->_row_pos, rhs->_row_pos, index, -1);
378
17.0M
        };
379
7.57k
        _sort_one_column(row_in_blocks, tie, cmp);
380
7.57k
    }
381
382
    // sort extra round by _row_pos to make the sort stable
383
3.12k
    auto iter = tie.iter();
384
238k
    while (iter.next()) {
385
235k
        pdqsort(std::next(row_in_blocks.begin(), iter.left()),
386
235k
                std::next(row_in_blocks.begin(), iter.right()),
387
1.69M
                [](const RowInBlock* lhs, const RowInBlock* rhs) -> bool {
388
1.69M
                    return lhs->_row_pos < rhs->_row_pos;
389
1.69M
                });
390
235k
    }
391
392
3.12k
    in_block = mutable_block.to_block();
393
3.12k
    SCOPED_RAW_TIMER(&_stat.put_into_output_ns);
394
3.12k
    DorisVector<uint32_t> row_pos_vec;
395
3.12k
    DCHECK(in_block.rows() <= std::numeric_limits<int>::max());
396
3.12k
    row_pos_vec.reserve(in_block.rows());
397
1.63M
    for (int i = 0; i < row_in_blocks.size(); i++) {
398
1.63M
        row_pos_vec.emplace_back(row_in_blocks[i]->_row_pos);
399
1.63M
    }
400
3.12k
    std::vector<int> column_offset;
401
43.3k
    for (int i = 0; i < _column_offset.size(); ++i) {
402
40.1k
        column_offset.emplace_back(i);
403
40.1k
    }
404
3.12k
    return _output_mutable_block.add_rows(&in_block, row_pos_vec.data(),
405
3.12k
                                          row_pos_vec.data() + in_block.rows(), &column_offset);
406
3.12k
}
407
408
void MemTable::_sort_one_column(DorisVector<RowInBlock*>& row_in_blocks, Tie& tie,
409
380k
                                std::function<int(const RowInBlock*, const RowInBlock*)> cmp) {
410
380k
    auto iter = tie.iter();
411
12.5M
    while (iter.next()) {
412
12.1M
        pdqsort(std::next(row_in_blocks.begin(), static_cast<int>(iter.left())),
413
12.1M
                std::next(row_in_blocks.begin(), static_cast<int>(iter.right())),
414
617M
                [&cmp](auto lhs, auto rhs) -> bool { return cmp(lhs, rhs) < 0; });
415
12.1M
        tie[iter.left()] = 0;
416
146M
        for (auto i = iter.left() + 1; i < iter.right(); i++) {
417
134M
            tie[i] = (cmp(row_in_blocks[i - 1], row_in_blocks[i]) == 0);
418
134M
        }
419
12.1M
    }
420
380k
}
421
422
template <bool is_final>
423
void MemTable::_finalize_one_row(RowInBlock* row,
424
                                 const vectorized::ColumnsWithTypeAndName& block_data,
425
644k
                                 int row_pos) {
426
    // move key columns
427
1.69M
    for (size_t i = 0; i < _tablet_schema->num_key_columns(); ++i) {
428
1.04M
        _output_mutable_block.get_column_by_position(i)->insert_from(*block_data[i].column.get(),
429
1.04M
                                                                     row->_row_pos);
430
1.04M
    }
431
644k
    if (row->has_init_agg()) {
432
        // get value columns from agg_places
433
169k
        for (size_t i = _tablet_schema->num_key_columns(); i < _num_columns; ++i) {
434
153k
            auto function = _agg_functions[i];
435
153k
            auto* agg_place = row->agg_places(i);
436
153k
            auto* col_ptr = _output_mutable_block.get_column_by_position(i).get();
437
153k
            function->insert_result_into(agg_place, *col_ptr);
438
439
153k
            if constexpr (is_final) {
440
0
                function->destroy(agg_place);
441
0
            } else {
442
0
                function->reset(agg_place);
443
0
            }
444
153k
        }
445
446
16.6k
        if constexpr (is_final) {
447
0
            row->remove_init_agg();
448
0
        } else {
449
0
            for (size_t i = _tablet_schema->num_key_columns(); i < _num_columns; ++i) {
450
0
                auto function = _agg_functions[i];
451
0
                auto* agg_place = row->agg_places(i);
452
0
                auto* col_ptr = _output_mutable_block.get_column_by_position(i).get();
453
0
                function->add(agg_place, const_cast<const doris::vectorized::IColumn**>(&col_ptr),
454
0
                              row_pos, _arena.get());
455
0
            }
456
0
        }
457
627k
    } else {
458
        // move columns for rows do not need agg
459
11.5M
        for (size_t i = _tablet_schema->num_key_columns(); i < _num_columns; ++i) {
460
10.9M
            _output_mutable_block.get_column_by_position(i)->insert_from(
461
10.9M
                    *block_data[i].column.get(), row->_row_pos);
462
10.9M
        }
463
627k
    }
464
644k
    if constexpr (!is_final) {
465
0
        row->_row_pos = row_pos;
466
0
    }
467
644k
}
Unexecuted instantiation: _ZN5doris8MemTable17_finalize_one_rowILb0EEEvPNS_10RowInBlockERKSt6vectorINS_10vectorized21ColumnWithTypeAndNameESaIS6_EEi
_ZN5doris8MemTable17_finalize_one_rowILb1EEEvPNS_10RowInBlockERKSt6vectorINS_10vectorized21ColumnWithTypeAndNameESaIS6_EEi
Line
Count
Source
425
644k
                                 int row_pos) {
426
    // move key columns
427
1.69M
    for (size_t i = 0; i < _tablet_schema->num_key_columns(); ++i) {
428
1.04M
        _output_mutable_block.get_column_by_position(i)->insert_from(*block_data[i].column.get(),
429
1.04M
                                                                     row->_row_pos);
430
1.04M
    }
431
644k
    if (row->has_init_agg()) {
432
        // get value columns from agg_places
433
169k
        for (size_t i = _tablet_schema->num_key_columns(); i < _num_columns; ++i) {
434
153k
            auto function = _agg_functions[i];
435
153k
            auto* agg_place = row->agg_places(i);
436
153k
            auto* col_ptr = _output_mutable_block.get_column_by_position(i).get();
437
153k
            function->insert_result_into(agg_place, *col_ptr);
438
439
153k
            if constexpr (is_final) {
440
152k
                function->destroy(agg_place);
441
152k
            } else {
442
153k
                function->reset(agg_place);
443
153k
            }
444
153k
        }
445
446
16.6k
        if constexpr (is_final) {
447
16.6k
            row->remove_init_agg();
448
16.6k
        } else {
449
16.6k
            for (size_t i = _tablet_schema->num_key_columns(); i < _num_columns; ++i) {
450
16.6k
                auto function = _agg_functions[i];
451
16.6k
                auto* agg_place = row->agg_places(i);
452
16.6k
                auto* col_ptr = _output_mutable_block.get_column_by_position(i).get();
453
16.6k
                function->add(agg_place, const_cast<const doris::vectorized::IColumn**>(&col_ptr),
454
16.6k
                              row_pos, _arena.get());
455
16.6k
            }
456
16.6k
        }
457
627k
    } else {
458
        // move columns for rows do not need agg
459
11.5M
        for (size_t i = _tablet_schema->num_key_columns(); i < _num_columns; ++i) {
460
10.9M
            _output_mutable_block.get_column_by_position(i)->insert_from(
461
10.9M
                    *block_data[i].column.get(), row->_row_pos);
462
10.9M
        }
463
627k
    }
464
644k
    if constexpr (!is_final) {
465
644k
        row->_row_pos = row_pos;
466
644k
    }
467
644k
}
468
469
template <bool is_final, bool has_skip_bitmap_col>
470
4.16k
void MemTable::_aggregate() {
471
4.16k
    SCOPED_RAW_TIMER(&_stat.agg_ns);
472
4.16k
    _stat.agg_times++;
473
4.16k
    vectorized::Block in_block = _input_mutable_block.to_block();
474
4.16k
    vectorized::MutableBlock mutable_block =
475
4.16k
            vectorized::MutableBlock::build_mutable_block(&in_block);
476
4.16k
    _vec_row_comparator->set_block(&mutable_block);
477
4.16k
    auto& block_data = in_block.get_columns_with_type_and_name();
478
4.16k
    DorisVector<RowInBlock*> temp_row_in_blocks;
479
4.16k
    temp_row_in_blocks.reserve(_last_sorted_pos);
480
4.16k
    RowInBlock* prev_row = nullptr;
481
4.16k
    int row_pos = -1;
482
    //only init agg if needed
483
484
16.6k
    auto init_for_agg = [&](RowInBlock* row) {
485
16.6k
        row->init_agg_places(_arena->aligned_alloc(_total_size_of_aggregate_states, 16),
486
16.6k
                             _offsets_of_aggregate_states.data());
487
169k
        for (auto cid = _tablet_schema->num_key_columns(); cid < _num_columns; cid++) {
488
152k
            auto* col_ptr = mutable_block.mutable_columns()[cid].get();
489
152k
            auto* data = prev_row->agg_places(cid);
490
152k
            _agg_functions[cid]->create(data);
491
152k
            _agg_functions[cid]->add(data, const_cast<const doris::vectorized::IColumn**>(&col_ptr),
492
152k
                                     prev_row->_row_pos, _arena.get());
493
152k
        }
494
16.6k
    };
Unexecuted instantiation: _ZZN5doris8MemTable10_aggregateILb0ELb0EEEvvENKUlPNS_10RowInBlockEE_clES3_
Unexecuted instantiation: _ZZN5doris8MemTable10_aggregateILb0ELb1EEEvvENKUlPNS_10RowInBlockEE_clES3_
_ZZN5doris8MemTable10_aggregateILb1ELb0EEEvvENKUlPNS_10RowInBlockEE_clES3_
Line
Count
Source
484
13.6k
    auto init_for_agg = [&](RowInBlock* row) {
485
13.6k
        row->init_agg_places(_arena->aligned_alloc(_total_size_of_aggregate_states, 16),
486
13.6k
                             _offsets_of_aggregate_states.data());
487
115k
        for (auto cid = _tablet_schema->num_key_columns(); cid < _num_columns; cid++) {
488
101k
            auto* col_ptr = mutable_block.mutable_columns()[cid].get();
489
101k
            auto* data = prev_row->agg_places(cid);
490
101k
            _agg_functions[cid]->create(data);
491
101k
            _agg_functions[cid]->add(data, const_cast<const doris::vectorized::IColumn**>(&col_ptr),
492
101k
                                     prev_row->_row_pos, _arena.get());
493
101k
        }
494
13.6k
    };
_ZZN5doris8MemTable10_aggregateILb1ELb1EEEvvENKUlPNS_10RowInBlockEE_clES3_
Line
Count
Source
484
3.00k
    auto init_for_agg = [&](RowInBlock* row) {
485
3.00k
        row->init_agg_places(_arena->aligned_alloc(_total_size_of_aggregate_states, 16),
486
3.00k
                             _offsets_of_aggregate_states.data());
487
54.0k
        for (auto cid = _tablet_schema->num_key_columns(); cid < _num_columns; cid++) {
488
51.0k
            auto* col_ptr = mutable_block.mutable_columns()[cid].get();
489
51.0k
            auto* data = prev_row->agg_places(cid);
490
51.0k
            _agg_functions[cid]->create(data);
491
51.0k
            _agg_functions[cid]->add(data, const_cast<const doris::vectorized::IColumn**>(&col_ptr),
492
51.0k
                                     prev_row->_row_pos, _arena.get());
493
51.0k
        }
494
3.00k
    };
495
496
4.16k
    if (!has_skip_bitmap_col || _seq_col_idx_in_block == -1) {
497
829k
        for (RowInBlock* cur_row : *_row_in_blocks) {
498
829k
            if (!temp_row_in_blocks.empty() && (*_vec_row_comparator)(prev_row, cur_row) == 0) {
499
185k
                if (!prev_row->has_init_agg()) {
500
16.4k
                    init_for_agg(prev_row);
501
16.4k
                }
502
185k
                _stat.merged_rows++;
503
185k
                _aggregate_two_row_in_block<has_skip_bitmap_col>(mutable_block, cur_row, prev_row);
504
643k
            } else {
505
643k
                prev_row = cur_row;
506
643k
                if (!temp_row_in_blocks.empty()) {
507
                    // no more rows to merge for prev row, finalize it
508
639k
                    _finalize_one_row<is_final>(temp_row_in_blocks.back(), block_data, row_pos);
509
639k
                }
510
643k
                temp_row_in_blocks.push_back(prev_row);
511
643k
                row_pos++;
512
643k
            }
513
829k
        }
514
4.13k
        if (!temp_row_in_blocks.empty()) {
515
            // finalize the last low
516
4.13k
            _finalize_one_row<is_final>(temp_row_in_blocks.back(), block_data, row_pos);
517
4.13k
        }
518
4.13k
    } else {
519
        // For flexible partial update and the table has sequence column, considering the following situation:
520
        // there are multiple rows with the same keys in memtable, some of them specify the sequence column,
521
        // some of them don't. We can't do the de-duplication in memtable becasue we can only know the value
522
        // of the sequence column of the row which don't specify seqeuence column in SegmentWriter after we
523
        // probe the historical data. So at here we can only merge rows that have sequence column together and
524
        // merge rows without sequence column together, and finally, perform deduplication on them in SegmentWriter.
525
526
        // !!ATTENTION!!: there may be rows with the same keys after MemTable::_aggregate() in this situation.
527
32
        RowInBlock* row_with_seq_col = nullptr;
528
32
        int row_pos_with_seq = -1;
529
32
        RowInBlock* row_without_seq_col = nullptr;
530
32
        int row_pos_without_seq = -1;
531
532
160
        auto finalize_rows = [&]() {
533
160
            if (row_with_seq_col != nullptr) {
534
128
                _finalize_one_row<is_final>(row_with_seq_col, block_data, row_pos_with_seq);
535
128
                row_with_seq_col = nullptr;
536
128
            }
537
160
            if (row_without_seq_col != nullptr) {
538
128
                _finalize_one_row<is_final>(row_without_seq_col, block_data, row_pos_without_seq);
539
128
                row_without_seq_col = nullptr;
540
128
            }
541
160
        };
Unexecuted instantiation: _ZZN5doris8MemTable10_aggregateILb0ELb1EEEvvENKUlvE_clEv
_ZZN5doris8MemTable10_aggregateILb1ELb1EEEvvENKUlvE_clEv
Line
Count
Source
532
160
        auto finalize_rows = [&]() {
533
160
            if (row_with_seq_col != nullptr) {
534
128
                _finalize_one_row<is_final>(row_with_seq_col, block_data, row_pos_with_seq);
535
128
                row_with_seq_col = nullptr;
536
128
            }
537
160
            if (row_without_seq_col != nullptr) {
538
128
                _finalize_one_row<is_final>(row_without_seq_col, block_data, row_pos_without_seq);
539
128
                row_without_seq_col = nullptr;
540
128
            }
541
160
        };
542
256
        auto add_row = [&](RowInBlock* row, bool with_seq_col) {
543
256
            temp_row_in_blocks.push_back(row);
544
256
            row_pos++;
545
256
            if (with_seq_col) {
546
128
                row_with_seq_col = row;
547
128
                row_pos_with_seq = row_pos;
548
128
            } else {
549
128
                row_without_seq_col = row;
550
128
                row_pos_without_seq = row_pos;
551
128
            }
552
256
        };
Unexecuted instantiation: _ZZN5doris8MemTable10_aggregateILb0ELb1EEEvvENKUlPNS_10RowInBlockEbE_clES3_b
_ZZN5doris8MemTable10_aggregateILb1ELb1EEEvvENKUlPNS_10RowInBlockEbE_clES3_b
Line
Count
Source
542
256
        auto add_row = [&](RowInBlock* row, bool with_seq_col) {
543
256
            temp_row_in_blocks.push_back(row);
544
256
            row_pos++;
545
256
            if (with_seq_col) {
546
128
                row_with_seq_col = row;
547
128
                row_pos_with_seq = row_pos;
548
128
            } else {
549
128
                row_without_seq_col = row;
550
128
                row_pos_without_seq = row_pos;
551
128
            }
552
256
        };
553
32
        auto& skip_bitmaps = assert_cast<vectorized::ColumnBitmap*>(
554
32
                                     mutable_block.mutable_columns()[_skip_bitmap_col_idx].get())
555
32
                                     ->get_data();
556
568
        for (auto* cur_row : *_row_in_blocks) {
557
568
            const BitmapValue& skip_bitmap = skip_bitmaps[cur_row->_row_pos];
558
568
            bool with_seq_col = !skip_bitmap.contains(_seq_col_unique_id);
559
            // compare keys, the keys of row_with_seq_col and row_with_seq_col is the same,
560
            // choose any of them if it's valid
561
568
            prev_row = (row_with_seq_col == nullptr) ? row_without_seq_col : row_with_seq_col;
562
568
            if (prev_row != nullptr && (*_vec_row_comparator)(prev_row, cur_row) == 0) {
563
440
                prev_row = (with_seq_col ? row_with_seq_col : row_without_seq_col);
564
440
                if (prev_row == nullptr) {
565
128
                    add_row(cur_row, with_seq_col);
566
128
                    continue;
567
128
                }
568
312
                if (!prev_row->has_init_agg()) {
569
144
                    init_for_agg(prev_row);
570
144
                }
571
312
                _stat.merged_rows++;
572
312
                _aggregate_two_row_in_block<has_skip_bitmap_col>(mutable_block, cur_row, prev_row);
573
312
            } else {
574
                // no more rows to merge for prev rows, finalize them
575
128
                finalize_rows();
576
128
                add_row(cur_row, with_seq_col);
577
128
            }
578
568
        }
579
        // finalize the last lows
580
32
        finalize_rows();
581
32
    }
582
4.16k
    if constexpr (!is_final) {
583
        // if is not final, we collect the agg results to input_block and then continue to insert
584
0
        _input_mutable_block.swap(_output_mutable_block);
585
        //TODO(weixang):opt here.
586
0
        std::unique_ptr<vectorized::Block> empty_input_block = in_block.create_same_struct_block(0);
587
0
        _output_mutable_block =
588
0
                vectorized::MutableBlock::build_mutable_block(empty_input_block.get());
589
0
        _output_mutable_block.clear_column_data();
590
0
        *_row_in_blocks = temp_row_in_blocks;
591
0
        _last_sorted_pos = _row_in_blocks->size();
592
0
    }
593
4.16k
}
Unexecuted instantiation: _ZN5doris8MemTable10_aggregateILb0ELb0EEEvv
Unexecuted instantiation: _ZN5doris8MemTable10_aggregateILb0ELb1EEEvv
_ZN5doris8MemTable10_aggregateILb1ELb0EEEvv
Line
Count
Source
470
3.81k
void MemTable::_aggregate() {
471
3.81k
    SCOPED_RAW_TIMER(&_stat.agg_ns);
472
3.81k
    _stat.agg_times++;
473
3.81k
    vectorized::Block in_block = _input_mutable_block.to_block();
474
3.81k
    vectorized::MutableBlock mutable_block =
475
3.81k
            vectorized::MutableBlock::build_mutable_block(&in_block);
476
3.81k
    _vec_row_comparator->set_block(&mutable_block);
477
3.81k
    auto& block_data = in_block.get_columns_with_type_and_name();
478
3.81k
    DorisVector<RowInBlock*> temp_row_in_blocks;
479
3.81k
    temp_row_in_blocks.reserve(_last_sorted_pos);
480
3.81k
    RowInBlock* prev_row = nullptr;
481
3.81k
    int row_pos = -1;
482
    //only init agg if needed
483
484
3.81k
    auto init_for_agg = [&](RowInBlock* row) {
485
3.81k
        row->init_agg_places(_arena->aligned_alloc(_total_size_of_aggregate_states, 16),
486
3.81k
                             _offsets_of_aggregate_states.data());
487
3.81k
        for (auto cid = _tablet_schema->num_key_columns(); cid < _num_columns; cid++) {
488
3.81k
            auto* col_ptr = mutable_block.mutable_columns()[cid].get();
489
3.81k
            auto* data = prev_row->agg_places(cid);
490
3.81k
            _agg_functions[cid]->create(data);
491
3.81k
            _agg_functions[cid]->add(data, const_cast<const doris::vectorized::IColumn**>(&col_ptr),
492
3.81k
                                     prev_row->_row_pos, _arena.get());
493
3.81k
        }
494
3.81k
    };
495
496
3.81k
    if (!has_skip_bitmap_col || _seq_col_idx_in_block == -1) {
497
818k
        for (RowInBlock* cur_row : *_row_in_blocks) {
498
818k
            if (!temp_row_in_blocks.empty() && (*_vec_row_comparator)(prev_row, cur_row) == 0) {
499
177k
                if (!prev_row->has_init_agg()) {
500
13.6k
                    init_for_agg(prev_row);
501
13.6k
                }
502
177k
                _stat.merged_rows++;
503
177k
                _aggregate_two_row_in_block<has_skip_bitmap_col>(mutable_block, cur_row, prev_row);
504
640k
            } else {
505
640k
                prev_row = cur_row;
506
640k
                if (!temp_row_in_blocks.empty()) {
507
                    // no more rows to merge for prev row, finalize it
508
636k
                    _finalize_one_row<is_final>(temp_row_in_blocks.back(), block_data, row_pos);
509
636k
                }
510
640k
                temp_row_in_blocks.push_back(prev_row);
511
640k
                row_pos++;
512
640k
            }
513
818k
        }
514
3.81k
        if (!temp_row_in_blocks.empty()) {
515
            // finalize the last low
516
3.81k
            _finalize_one_row<is_final>(temp_row_in_blocks.back(), block_data, row_pos);
517
3.81k
        }
518
3.81k
    } else {
519
        // For flexible partial update and the table has sequence column, considering the following situation:
520
        // there are multiple rows with the same keys in memtable, some of them specify the sequence column,
521
        // some of them don't. We can't do the de-duplication in memtable becasue we can only know the value
522
        // of the sequence column of the row which don't specify seqeuence column in SegmentWriter after we
523
        // probe the historical data. So at here we can only merge rows that have sequence column together and
524
        // merge rows without sequence column together, and finally, perform deduplication on them in SegmentWriter.
525
526
        // !!ATTENTION!!: there may be rows with the same keys after MemTable::_aggregate() in this situation.
527
0
        RowInBlock* row_with_seq_col = nullptr;
528
0
        int row_pos_with_seq = -1;
529
0
        RowInBlock* row_without_seq_col = nullptr;
530
0
        int row_pos_without_seq = -1;
531
532
0
        auto finalize_rows = [&]() {
533
0
            if (row_with_seq_col != nullptr) {
534
0
                _finalize_one_row<is_final>(row_with_seq_col, block_data, row_pos_with_seq);
535
0
                row_with_seq_col = nullptr;
536
0
            }
537
0
            if (row_without_seq_col != nullptr) {
538
0
                _finalize_one_row<is_final>(row_without_seq_col, block_data, row_pos_without_seq);
539
0
                row_without_seq_col = nullptr;
540
0
            }
541
0
        };
542
0
        auto add_row = [&](RowInBlock* row, bool with_seq_col) {
543
0
            temp_row_in_blocks.push_back(row);
544
0
            row_pos++;
545
0
            if (with_seq_col) {
546
0
                row_with_seq_col = row;
547
0
                row_pos_with_seq = row_pos;
548
0
            } else {
549
0
                row_without_seq_col = row;
550
0
                row_pos_without_seq = row_pos;
551
0
            }
552
0
        };
553
0
        auto& skip_bitmaps = assert_cast<vectorized::ColumnBitmap*>(
554
0
                                     mutable_block.mutable_columns()[_skip_bitmap_col_idx].get())
555
0
                                     ->get_data();
556
0
        for (auto* cur_row : *_row_in_blocks) {
557
0
            const BitmapValue& skip_bitmap = skip_bitmaps[cur_row->_row_pos];
558
0
            bool with_seq_col = !skip_bitmap.contains(_seq_col_unique_id);
559
            // compare keys, the keys of row_with_seq_col and row_with_seq_col is the same,
560
            // choose any of them if it's valid
561
0
            prev_row = (row_with_seq_col == nullptr) ? row_without_seq_col : row_with_seq_col;
562
0
            if (prev_row != nullptr && (*_vec_row_comparator)(prev_row, cur_row) == 0) {
563
0
                prev_row = (with_seq_col ? row_with_seq_col : row_without_seq_col);
564
0
                if (prev_row == nullptr) {
565
0
                    add_row(cur_row, with_seq_col);
566
0
                    continue;
567
0
                }
568
0
                if (!prev_row->has_init_agg()) {
569
0
                    init_for_agg(prev_row);
570
0
                }
571
0
                _stat.merged_rows++;
572
0
                _aggregate_two_row_in_block<has_skip_bitmap_col>(mutable_block, cur_row, prev_row);
573
0
            } else {
574
                // no more rows to merge for prev rows, finalize them
575
0
                finalize_rows();
576
0
                add_row(cur_row, with_seq_col);
577
0
            }
578
0
        }
579
        // finalize the last lows
580
0
        finalize_rows();
581
0
    }
582
3.81k
    if constexpr (!is_final) {
583
        // if is not final, we collect the agg results to input_block and then continue to insert
584
3.81k
        _input_mutable_block.swap(_output_mutable_block);
585
        //TODO(weixang):opt here.
586
3.81k
        std::unique_ptr<vectorized::Block> empty_input_block = in_block.create_same_struct_block(0);
587
3.81k
        _output_mutable_block =
588
3.81k
                vectorized::MutableBlock::build_mutable_block(empty_input_block.get());
589
3.81k
        _output_mutable_block.clear_column_data();
590
3.81k
        *_row_in_blocks = temp_row_in_blocks;
591
3.81k
        _last_sorted_pos = _row_in_blocks->size();
592
3.81k
    }
593
3.81k
}
_ZN5doris8MemTable10_aggregateILb1ELb1EEEvv
Line
Count
Source
470
348
void MemTable::_aggregate() {
471
348
    SCOPED_RAW_TIMER(&_stat.agg_ns);
472
348
    _stat.agg_times++;
473
348
    vectorized::Block in_block = _input_mutable_block.to_block();
474
348
    vectorized::MutableBlock mutable_block =
475
348
            vectorized::MutableBlock::build_mutable_block(&in_block);
476
348
    _vec_row_comparator->set_block(&mutable_block);
477
348
    auto& block_data = in_block.get_columns_with_type_and_name();
478
348
    DorisVector<RowInBlock*> temp_row_in_blocks;
479
348
    temp_row_in_blocks.reserve(_last_sorted_pos);
480
348
    RowInBlock* prev_row = nullptr;
481
348
    int row_pos = -1;
482
    //only init agg if needed
483
484
348
    auto init_for_agg = [&](RowInBlock* row) {
485
348
        row->init_agg_places(_arena->aligned_alloc(_total_size_of_aggregate_states, 16),
486
348
                             _offsets_of_aggregate_states.data());
487
348
        for (auto cid = _tablet_schema->num_key_columns(); cid < _num_columns; cid++) {
488
348
            auto* col_ptr = mutable_block.mutable_columns()[cid].get();
489
348
            auto* data = prev_row->agg_places(cid);
490
348
            _agg_functions[cid]->create(data);
491
348
            _agg_functions[cid]->add(data, const_cast<const doris::vectorized::IColumn**>(&col_ptr),
492
348
                                     prev_row->_row_pos, _arena.get());
493
348
        }
494
348
    };
495
496
348
    if (!has_skip_bitmap_col || _seq_col_idx_in_block == -1) {
497
11.3k
        for (RowInBlock* cur_row : *_row_in_blocks) {
498
11.3k
            if (!temp_row_in_blocks.empty() && (*_vec_row_comparator)(prev_row, cur_row) == 0) {
499
7.88k
                if (!prev_row->has_init_agg()) {
500
2.86k
                    init_for_agg(prev_row);
501
2.86k
                }
502
7.88k
                _stat.merged_rows++;
503
7.88k
                _aggregate_two_row_in_block<has_skip_bitmap_col>(mutable_block, cur_row, prev_row);
504
7.88k
            } else {
505
3.47k
                prev_row = cur_row;
506
3.47k
                if (!temp_row_in_blocks.empty()) {
507
                    // no more rows to merge for prev row, finalize it
508
3.17k
                    _finalize_one_row<is_final>(temp_row_in_blocks.back(), block_data, row_pos);
509
3.17k
                }
510
3.47k
                temp_row_in_blocks.push_back(prev_row);
511
3.47k
                row_pos++;
512
3.47k
            }
513
11.3k
        }
514
316
        if (!temp_row_in_blocks.empty()) {
515
            // finalize the last low
516
314
            _finalize_one_row<is_final>(temp_row_in_blocks.back(), block_data, row_pos);
517
314
        }
518
316
    } else {
519
        // For flexible partial update and the table has sequence column, considering the following situation:
520
        // there are multiple rows with the same keys in memtable, some of them specify the sequence column,
521
        // some of them don't. We can't do the de-duplication in memtable becasue we can only know the value
522
        // of the sequence column of the row which don't specify seqeuence column in SegmentWriter after we
523
        // probe the historical data. So at here we can only merge rows that have sequence column together and
524
        // merge rows without sequence column together, and finally, perform deduplication on them in SegmentWriter.
525
526
        // !!ATTENTION!!: there may be rows with the same keys after MemTable::_aggregate() in this situation.
527
32
        RowInBlock* row_with_seq_col = nullptr;
528
32
        int row_pos_with_seq = -1;
529
32
        RowInBlock* row_without_seq_col = nullptr;
530
32
        int row_pos_without_seq = -1;
531
532
32
        auto finalize_rows = [&]() {
533
32
            if (row_with_seq_col != nullptr) {
534
32
                _finalize_one_row<is_final>(row_with_seq_col, block_data, row_pos_with_seq);
535
32
                row_with_seq_col = nullptr;
536
32
            }
537
32
            if (row_without_seq_col != nullptr) {
538
32
                _finalize_one_row<is_final>(row_without_seq_col, block_data, row_pos_without_seq);
539
32
                row_without_seq_col = nullptr;
540
32
            }
541
32
        };
542
32
        auto add_row = [&](RowInBlock* row, bool with_seq_col) {
543
32
            temp_row_in_blocks.push_back(row);
544
32
            row_pos++;
545
32
            if (with_seq_col) {
546
32
                row_with_seq_col = row;
547
32
                row_pos_with_seq = row_pos;
548
32
            } else {
549
32
                row_without_seq_col = row;
550
32
                row_pos_without_seq = row_pos;
551
32
            }
552
32
        };
553
32
        auto& skip_bitmaps = assert_cast<vectorized::ColumnBitmap*>(
554
32
                                     mutable_block.mutable_columns()[_skip_bitmap_col_idx].get())
555
32
                                     ->get_data();
556
568
        for (auto* cur_row : *_row_in_blocks) {
557
568
            const BitmapValue& skip_bitmap = skip_bitmaps[cur_row->_row_pos];
558
568
            bool with_seq_col = !skip_bitmap.contains(_seq_col_unique_id);
559
            // compare keys, the keys of row_with_seq_col and row_with_seq_col is the same,
560
            // choose any of them if it's valid
561
568
            prev_row = (row_with_seq_col == nullptr) ? row_without_seq_col : row_with_seq_col;
562
568
            if (prev_row != nullptr && (*_vec_row_comparator)(prev_row, cur_row) == 0) {
563
440
                prev_row = (with_seq_col ? row_with_seq_col : row_without_seq_col);
564
440
                if (prev_row == nullptr) {
565
128
                    add_row(cur_row, with_seq_col);
566
128
                    continue;
567
128
                }
568
312
                if (!prev_row->has_init_agg()) {
569
144
                    init_for_agg(prev_row);
570
144
                }
571
312
                _stat.merged_rows++;
572
312
                _aggregate_two_row_in_block<has_skip_bitmap_col>(mutable_block, cur_row, prev_row);
573
312
            } else {
574
                // no more rows to merge for prev rows, finalize them
575
128
                finalize_rows();
576
128
                add_row(cur_row, with_seq_col);
577
128
            }
578
568
        }
579
        // finalize the last lows
580
32
        finalize_rows();
581
32
    }
582
348
    if constexpr (!is_final) {
583
        // if is not final, we collect the agg results to input_block and then continue to insert
584
348
        _input_mutable_block.swap(_output_mutable_block);
585
        //TODO(weixang):opt here.
586
348
        std::unique_ptr<vectorized::Block> empty_input_block = in_block.create_same_struct_block(0);
587
348
        _output_mutable_block =
588
348
                vectorized::MutableBlock::build_mutable_block(empty_input_block.get());
589
348
        _output_mutable_block.clear_column_data();
590
348
        *_row_in_blocks = temp_row_in_blocks;
591
348
        _last_sorted_pos = _row_in_blocks->size();
592
348
    }
593
348
}
594
595
0
void MemTable::shrink_memtable_by_agg() {
596
0
    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(
597
0
            _resource_ctx->memory_context()->mem_tracker()->write_tracker());
598
0
    SCOPED_CONSUME_MEM_TRACKER(_mem_tracker);
599
0
    if (_keys_type == KeysType::DUP_KEYS) {
600
0
        return;
601
0
    }
602
0
    size_t same_keys_num = _sort();
603
0
    if (same_keys_num != 0) {
604
0
        (_skip_bitmap_col_idx == -1) ? _aggregate<false, false>() : _aggregate<false, true>();
605
0
    }
606
0
}
607
608
279k
bool MemTable::need_flush() const {
609
279k
    DBUG_EXECUTE_IF("MemTable.need_flush", { return true; });
610
279k
    auto max_size = config::write_buffer_size;
611
279k
    if (_partial_update_mode == UniqueKeyUpdateModePB::UPDATE_FIXED_COLUMNS) {
612
1.93k
        auto update_columns_size = _num_columns;
613
1.93k
        max_size = max_size * update_columns_size / _tablet_schema->num_columns();
614
1.93k
        max_size = max_size > 1048576 ? max_size : 1048576;
615
1.93k
    }
616
279k
    return memory_usage() >= max_size;
617
279k
}
618
619
279k
bool MemTable::need_agg() const {
620
279k
    if (_keys_type == KeysType::AGG_KEYS) {
621
8.90k
        auto max_size = config::write_buffer_size_for_agg;
622
8.90k
        return memory_usage() >= max_size;
623
8.90k
    }
624
270k
    return false;
625
279k
}
626
627
127k
size_t MemTable::get_flush_reserve_memory_size() const {
628
127k
    if (_keys_type == KeysType::DUP_KEYS && _tablet_schema->num_key_columns() == 0) {
629
44
        return 0; // no need to reserve
630
44
    }
631
127k
    return static_cast<size_t>(static_cast<double>(_input_mutable_block.allocated_bytes()) * 1.2);
632
127k
}
633
634
127k
Status MemTable::_to_block(std::unique_ptr<vectorized::Block>* res) {
635
127k
    size_t same_keys_num = _sort();
636
127k
    if (_keys_type == KeysType::DUP_KEYS || same_keys_num == 0) {
637
123k
        if (_keys_type == KeysType::DUP_KEYS && _tablet_schema->num_key_columns() == 0) {
638
44
            _output_mutable_block.swap(_input_mutable_block);
639
123k
        } else {
640
123k
            vectorized::Block in_block = _input_mutable_block.to_block();
641
123k
            RETURN_IF_ERROR(_put_into_output(in_block));
642
123k
        }
643
123k
    } else {
644
4.13k
        (_skip_bitmap_col_idx == -1) ? _aggregate<true, false>() : _aggregate<true, true>();
645
4.13k
    }
646
127k
    if (_keys_type == KeysType::UNIQUE_KEYS && _enable_unique_key_mow &&
647
127k
        !_tablet_schema->cluster_key_uids().empty()) {
648
3.12k
        if (_partial_update_mode != UniqueKeyUpdateModePB::UPSERT) {
649
0
            return Status::InternalError(
650
0
                    "Partial update for mow with cluster keys is not supported");
651
0
        }
652
3.12k
        RETURN_IF_ERROR(_sort_by_cluster_keys());
653
3.12k
    }
654
127k
    _input_mutable_block.clear();
655
127k
    *res = vectorized::Block::create_unique(_output_mutable_block.to_block());
656
127k
    return Status::OK();
657
127k
}
658
659
127k
Status MemTable::to_block(std::unique_ptr<vectorized::Block>* res) {
660
127k
    RETURN_IF_ERROR_OR_CATCH_EXCEPTION(_to_block(res));
661
127k
    return Status::OK();
662
127k
}
663
664
#include "common/compile_check_end.h"
665
} // namespace doris