Coverage Report

Created: 2026-02-03 19:46

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/doris/be/src/olap/memtable.cpp
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "olap/memtable.h"
19
20
#include <fmt/format.h>
21
#include <gen_cpp/olap_file.pb.h>
22
#include <pdqsort.h>
23
24
#include <algorithm>
25
#include <limits>
26
#include <string>
27
#include <vector>
28
29
#include "bvar/bvar.h"
30
#include "common/config.h"
31
#include "olap/memtable_memory_limiter.h"
32
#include "olap/olap_define.h"
33
#include "olap/tablet_schema.h"
34
#include "runtime/descriptors.h"
35
#include "runtime/exec_env.h"
36
#include "runtime/thread_context.h"
37
#include "util/debug_points.h"
38
#include "util/runtime_profile.h"
39
#include "util/stopwatch.hpp"
40
#include "vec/aggregate_functions/aggregate_function_reader.h"
41
#include "vec/aggregate_functions/aggregate_function_simple_factory.h"
42
#include "vec/columns/column.h"
43
44
namespace doris {
45
#include "common/compile_check_begin.h"
46
47
bvar::Adder<int64_t> g_memtable_cnt("memtable_cnt");
48
bvar::Adder<uint64_t> g_flush_cuz_memtable_full("flush_cuz_memtable_full");
49
50
using namespace ErrorCode;
51
52
MemTable::MemTable(int64_t tablet_id, std::shared_ptr<TabletSchema> tablet_schema,
53
                   const std::vector<SlotDescriptor*>* slot_descs, TupleDescriptor* tuple_desc,
54
                   bool enable_unique_key_mow, PartialUpdateInfo* partial_update_info,
55
                   const std::shared_ptr<ResourceContext>& resource_ctx, int64_t rows_of_segment)
56
15
        : _mem_type(MemType::ACTIVE),
57
15
          _tablet_id(tablet_id),
58
15
          _enable_unique_key_mow(enable_unique_key_mow),
59
15
          _keys_type(tablet_schema->keys_type()),
60
15
          _tablet_schema(tablet_schema),
61
15
          _rows_of_segment(rows_of_segment),
62
15
          _resource_ctx(resource_ctx),
63
15
          _is_first_insertion(true),
64
15
          _agg_functions(tablet_schema->num_columns()),
65
15
          _offsets_of_aggregate_states(tablet_schema->num_columns()),
66
15
          _total_size_of_aggregate_states(0) {
67
15
    g_memtable_cnt << 1;
68
15
    _mem_tracker = std::make_shared<MemTracker>();
69
15
    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(
70
15
            _resource_ctx->memory_context()->mem_tracker()->write_tracker());
71
15
    SCOPED_CONSUME_MEM_TRACKER(_mem_tracker);
72
15
    _vec_row_comparator = std::make_shared<RowInBlockComparator>(_tablet_schema);
73
15
    if (partial_update_info != nullptr) {
74
15
        _partial_update_mode = partial_update_info->update_mode();
75
15
        if (_partial_update_mode == UniqueKeyUpdateModePB::UPDATE_FIXED_COLUMNS) {
76
0
            if (partial_update_info->is_schema_contains_auto_inc_column &&
77
0
                !partial_update_info->is_input_columns_contains_auto_inc_column) {
78
0
                _is_partial_update_and_auto_inc = true;
79
0
            }
80
0
        }
81
15
    }
82
15
    _init_columns_offset_by_slot_descs(slot_descs, tuple_desc);
83
    // TODO: Support ZOrderComparator in the future
84
15
    _row_in_blocks = std::make_unique<DorisVector<std::shared_ptr<RowInBlock>>>();
85
15
    _load_mem_limit = MemInfo::mem_limit() * config::load_process_max_memory_limit_percent / 100;
86
15
}
87
88
void MemTable::_init_columns_offset_by_slot_descs(const std::vector<SlotDescriptor*>* slot_descs,
89
15
                                                  const TupleDescriptor* tuple_desc) {
90
91
    for (auto slot_desc : *slot_descs) {
91
91
        const auto& slots = tuple_desc->slots();
92
630
        for (int j = 0; j < slots.size(); ++j) {
93
630
            if (slot_desc->id() == slots[j]->id()) {
94
91
                _column_offset.emplace_back(j);
95
91
                break;
96
91
            }
97
630
        }
98
91
    }
99
15
    if (_is_partial_update_and_auto_inc) {
100
0
        _column_offset.emplace_back(_column_offset.size());
101
0
    }
102
15
    _num_columns = _column_offset.size();
103
15
}
104
105
12
void MemTable::_init_agg_functions(const vectorized::Block* block) {
106
12
    if (_num_columns > _column_offset.size()) [[unlikely]] {
107
0
        throw doris::Exception(doris::ErrorCode::INTERNAL_ERROR,
108
0
                               "num_columns {} is greater than block columns {}", _num_columns,
109
0
                               _column_offset.size());
110
0
    }
111
42
    for (auto cid = _tablet_schema->num_key_columns(); cid < _num_columns; ++cid) {
112
30
        vectorized::AggregateFunctionPtr function;
113
30
        if (_keys_type == KeysType::UNIQUE_KEYS && _enable_unique_key_mow) {
114
            // In such table, non-key column's aggregation type is NONE, so we need to construct
115
            // the aggregate function manually.
116
9
            if (_skip_bitmap_col_idx != cid) {
117
9
                function = vectorized::AggregateFunctionSimpleFactory::instance().get(
118
9
                        "replace_load", {block->get_data_type(cid)}, block->get_data_type(cid),
119
9
                        block->get_data_type(cid)->is_nullable(),
120
9
                        BeExecVersionManager::get_newest_version());
121
9
            } else {
122
0
                function = vectorized::AggregateFunctionSimpleFactory::instance().get(
123
0
                        "bitmap_intersect", {block->get_data_type(cid)}, block->get_data_type(cid),
124
0
                        false, BeExecVersionManager::get_newest_version());
125
0
            }
126
21
        } else {
127
21
            function = _tablet_schema->column(cid).get_aggregate_function(
128
21
                    vectorized::AGG_LOAD_SUFFIX, _tablet_schema->column(cid).get_be_exec_version());
129
21
            if (function == nullptr) {
130
0
                LOG(WARNING) << "column get aggregate function failed, column="
131
0
                             << _tablet_schema->column(cid).name();
132
0
            }
133
21
        }
134
135
30
        DCHECK(function != nullptr);
136
30
        _agg_functions[cid] = function;
137
30
    }
138
139
42
    for (auto cid = _tablet_schema->num_key_columns(); cid < _num_columns; ++cid) {
140
30
        _offsets_of_aggregate_states[cid] = _total_size_of_aggregate_states;
141
30
        _total_size_of_aggregate_states += _agg_functions[cid]->size_of_data();
142
143
        // If not the last aggregate_state, we need pad it so that next aggregate_state will be aligned.
144
30
        if (cid + 1 < _num_columns) {
145
22
            size_t alignment_of_next_state = _agg_functions[cid + 1]->align_of_data();
146
147
            /// Extend total_size to next alignment requirement
148
            /// Add padding by rounding up 'total_size_of_aggregate_states' to be a multiplier of alignment_of_next_state.
149
22
            _total_size_of_aggregate_states =
150
22
                    (_total_size_of_aggregate_states + alignment_of_next_state - 1) /
151
22
                    alignment_of_next_state * alignment_of_next_state;
152
22
        }
153
30
    }
154
12
}
155
156
15
MemTable::~MemTable() {
157
15
    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(
158
15
            _resource_ctx->memory_context()->mem_tracker()->write_tracker());
159
15
    {
160
15
        SCOPED_CONSUME_MEM_TRACKER(_mem_tracker);
161
15
        g_memtable_cnt << -1;
162
15
        if (_keys_type != KeysType::DUP_KEYS) {
163
35
            for (auto it = _row_in_blocks->begin(); it != _row_in_blocks->end(); it++) {
164
20
                if (!(*it)->has_init_agg()) {
165
20
                    continue;
166
20
                }
167
                // We should release agg_places here, because they are not released when a
168
                // load is canceled.
169
0
                for (size_t i = _tablet_schema->num_key_columns(); i < _num_columns; ++i) {
170
0
                    auto function = _agg_functions[i];
171
0
                    DCHECK(function != nullptr);
172
0
                    function->destroy((*it)->agg_places(i));
173
0
                }
174
0
            }
175
15
        }
176
177
15
        _arena.clear(true);
178
15
        _vec_row_comparator.reset();
179
15
        _row_in_blocks.reset();
180
15
        _agg_functions.clear();
181
15
        _input_mutable_block.clear();
182
15
        _output_mutable_block.clear();
183
15
    }
184
15
    if (_is_flush_success) {
185
        // If the memtable is flush success, then its memtracker's consumption should be 0
186
12
        if (_mem_tracker->consumption() != 0 && config::crash_in_memory_tracker_inaccurate) {
187
0
            LOG(FATAL) << "memtable flush success but cosumption is not 0, it is "
188
0
                       << _mem_tracker->consumption();
189
0
        }
190
12
    }
191
15
}
192
193
6
int RowInBlockComparator::operator()(const RowInBlock* left, const RowInBlock* right) const {
194
6
    return _pblock->compare_at(left->_row_pos, right->_row_pos, _tablet_schema->num_key_columns(),
195
6
                               *_pblock, -1);
196
6
}
197
198
Status MemTable::insert(const vectorized::Block* input_block,
199
20
                        const DorisVector<uint32_t>& row_idxs) {
200
20
    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(
201
20
            _resource_ctx->memory_context()->mem_tracker()->write_tracker());
202
20
    SCOPED_CONSUME_MEM_TRACKER(_mem_tracker);
203
204
20
    if (_is_first_insertion) {
205
12
        _is_first_insertion = false;
206
12
        auto clone_block = input_block->clone_without_columns(&_column_offset);
207
12
        _input_mutable_block = vectorized::MutableBlock::build_mutable_block(&clone_block);
208
12
        _vec_row_comparator->set_block(&_input_mutable_block);
209
12
        _output_mutable_block = vectorized::MutableBlock::build_mutable_block(&clone_block);
210
12
        if (_tablet_schema->has_sequence_col()) {
211
7
            if (_partial_update_mode == UniqueKeyUpdateModePB::UPDATE_FIXED_COLUMNS) {
212
                // for unique key fixed partial update, sequence column index in block
213
                // may be different with the index in `_tablet_schema`
214
0
                for (int32_t i = 0; i < clone_block.columns(); i++) {
215
0
                    if (clone_block.get_by_position(i).name == SEQUENCE_COL) {
216
0
                        _seq_col_idx_in_block = i;
217
0
                        break;
218
0
                    }
219
0
                }
220
7
            } else {
221
7
                _seq_col_idx_in_block = _tablet_schema->sequence_col_idx();
222
7
            }
223
7
        }
224
12
        if (_partial_update_mode == UniqueKeyUpdateModePB::UPDATE_FLEXIBLE_COLUMNS &&
225
12
            _tablet_schema->has_skip_bitmap_col()) {
226
            // init of _skip_bitmap_col_idx and _delete_sign_col_idx must be before _init_agg_functions()
227
0
            _skip_bitmap_col_idx = _tablet_schema->skip_bitmap_col_idx();
228
0
            _delete_sign_col_idx = _tablet_schema->delete_sign_idx();
229
0
            _delete_sign_col_unique_id = _tablet_schema->column(_delete_sign_col_idx).unique_id();
230
0
            if (_seq_col_idx_in_block != -1) {
231
0
                _seq_col_unique_id = _tablet_schema->column(_seq_col_idx_in_block).unique_id();
232
0
            }
233
0
        }
234
12
        if (_keys_type != KeysType::DUP_KEYS) {
235
            // there may be additional intermediate columns in input_block
236
            // we only need columns indicated by column offset in the output
237
12
            RETURN_IF_CATCH_EXCEPTION(_init_agg_functions(&clone_block));
238
12
        }
239
12
    }
240
241
20
    auto num_rows = row_idxs.size();
242
20
    size_t cursor_in_mutableblock = _input_mutable_block.rows();
243
20
    RETURN_IF_ERROR(_input_mutable_block.add_rows(input_block, row_idxs.data(),
244
20
                                                  row_idxs.data() + num_rows, &_column_offset));
245
40
    for (int i = 0; i < num_rows; i++) {
246
20
        _row_in_blocks->emplace_back(std::make_shared<RowInBlock>(cursor_in_mutableblock + i));
247
20
    }
248
249
20
    _stat.raw_rows += num_rows;
250
251
20
    LOG(INFO) << "MemTable::insert block to memtable: tablet_id=" << _tablet_id
252
20
              << ", input_block_rows=" << input_block->rows() << ", inserted_rows=" << num_rows
253
20
              << ", memtable_total_rows=" << _stat.raw_rows
254
20
              << ", memtable_memory=" << memory_usage();
255
20
    return Status::OK();
256
20
}
257
258
void MemTable::_aggregate_two_row_with_sequence_map(vectorized::MutableBlock& mutable_block,
259
0
                                                    RowInBlock* src_row, RowInBlock* dst_row) {
260
    // for each mapping replace value columns according to the sequence column compare result
261
    // for example: a b c d s1 s2  (key:a , s1=>[b,c], s2=>[d])
262
    // src row:     1 4 5 6  8 9
263
    // dst row:     1 2 3 4  7 10
264
    // after aggregate
265
    // dst row:     1 4 5 4  8 10  (b,c,s1 will be replaced, d,s2)
266
0
    const auto& seq_map = _tablet_schema->seq_col_idx_to_value_cols_idx();
267
0
    for (const auto& it : seq_map) {
268
0
        auto sequence = it.first;
269
0
        auto* sequence_col_ptr = mutable_block.mutable_columns()[sequence].get();
270
0
        auto res = sequence_col_ptr->compare_at(dst_row->_row_pos, src_row->_row_pos,
271
0
                                                *sequence_col_ptr, -1);
272
0
        if (res > 0) {
273
0
            continue;
274
0
        }
275
0
        for (auto cid : it.second) {
276
0
            if (cid < _num_columns) {
277
0
                auto* col_ptr = mutable_block.mutable_columns()[cid].get();
278
0
                _agg_functions[cid]->add(dst_row->agg_places(cid),
279
0
                                         const_cast<const doris::vectorized::IColumn**>(&col_ptr),
280
0
                                         src_row->_row_pos, _arena);
281
0
            }
282
0
        }
283
0
        if (sequence < _num_columns) {
284
0
            _agg_functions[sequence]->add(
285
0
                    dst_row->agg_places(sequence),
286
0
                    const_cast<const doris::vectorized::IColumn**>(&sequence_col_ptr),
287
0
                    src_row->_row_pos, _arena);
288
            // must use replace column instead of update row_pos
289
            // because one row may have multi sequence column
290
            // and agg function add method won't change the real column value
291
0
            sequence_col_ptr->replace_column_data(*sequence_col_ptr, src_row->_row_pos,
292
0
                                                  dst_row->_row_pos);
293
0
        }
294
0
    }
295
0
}
296
297
template <bool has_skip_bitmap_col>
298
void MemTable::_aggregate_two_row_in_block(vectorized::MutableBlock& mutable_block,
299
3
                                           RowInBlock* src_row, RowInBlock* dst_row) {
300
    // for flexible partial update, the caller must guarantees that either src_row and dst_row
301
    // both specify the sequence column, or src_row and dst_row both don't specify the
302
    // sequence column
303
3
    if (_tablet_schema->has_sequence_col() && _seq_col_idx_in_block >= 0) {
304
3
        DCHECK_LT(_seq_col_idx_in_block, mutable_block.columns());
305
3
        auto col_ptr = mutable_block.mutable_columns()[_seq_col_idx_in_block].get();
306
3
        auto res = col_ptr->compare_at(dst_row->_row_pos, src_row->_row_pos, *col_ptr, -1);
307
        // dst sequence column larger than src, don't need to update
308
3
        if (res > 0) {
309
3
            return;
310
3
        }
311
        // need to update the row pos in dst row to the src row pos when has
312
        // sequence column
313
0
        dst_row->_row_pos = src_row->_row_pos;
314
0
    }
315
    // dst is non-sequence row, or dst sequence is smaller
316
0
    if constexpr (!has_skip_bitmap_col) {
317
0
        DCHECK(_skip_bitmap_col_idx == -1);
318
0
        for (size_t cid = _tablet_schema->num_key_columns(); cid < _num_columns; ++cid) {
319
0
            auto* col_ptr = mutable_block.mutable_columns()[cid].get();
320
0
            _agg_functions[cid]->add(dst_row->agg_places(cid),
321
0
                                     const_cast<const doris::vectorized::IColumn**>(&col_ptr),
322
0
                                     src_row->_row_pos, _arena);
323
0
        }
324
0
    } else {
325
0
        DCHECK(_skip_bitmap_col_idx != -1);
326
0
        DCHECK_LT(_skip_bitmap_col_idx, mutable_block.columns());
327
0
        const BitmapValue& skip_bitmap =
328
0
                assert_cast<vectorized::ColumnBitmap*, TypeCheckOnRelease::DISABLE>(
329
0
                        mutable_block.mutable_columns()[_skip_bitmap_col_idx].get())
330
0
                        ->get_data()[src_row->_row_pos];
331
0
        for (size_t cid = _tablet_schema->num_key_columns(); cid < _num_columns; ++cid) {
332
0
            const auto& col = _tablet_schema->column(cid);
333
0
            if (cid != _skip_bitmap_col_idx && skip_bitmap.contains(col.unique_id())) {
334
0
                continue;
335
0
            }
336
0
            auto* col_ptr = mutable_block.mutable_columns()[cid].get();
337
0
            _agg_functions[cid]->add(dst_row->agg_places(cid),
338
0
                                     const_cast<const doris::vectorized::IColumn**>(&col_ptr),
339
0
                                     src_row->_row_pos, _arena);
340
0
        }
341
0
    }
342
0
}
_ZN5doris8MemTable27_aggregate_two_row_in_blockILb0EEEvRNS_10vectorized12MutableBlockEPNS_10RowInBlockES6_
Line
Count
Source
299
3
                                           RowInBlock* src_row, RowInBlock* dst_row) {
300
    // for flexible partial update, the caller must guarantees that either src_row and dst_row
301
    // both specify the sequence column, or src_row and dst_row both don't specify the
302
    // sequence column
303
3
    if (_tablet_schema->has_sequence_col() && _seq_col_idx_in_block >= 0) {
304
3
        DCHECK_LT(_seq_col_idx_in_block, mutable_block.columns());
305
3
        auto col_ptr = mutable_block.mutable_columns()[_seq_col_idx_in_block].get();
306
3
        auto res = col_ptr->compare_at(dst_row->_row_pos, src_row->_row_pos, *col_ptr, -1);
307
        // dst sequence column larger than src, don't need to update
308
3
        if (res > 0) {
309
3
            return;
310
3
        }
311
        // need to update the row pos in dst row to the src row pos when has
312
        // sequence column
313
0
        dst_row->_row_pos = src_row->_row_pos;
314
0
    }
315
    // dst is non-sequence row, or dst sequence is smaller
316
0
    if constexpr (!has_skip_bitmap_col) {
317
0
        DCHECK(_skip_bitmap_col_idx == -1);
318
0
        for (size_t cid = _tablet_schema->num_key_columns(); cid < _num_columns; ++cid) {
319
0
            auto* col_ptr = mutable_block.mutable_columns()[cid].get();
320
0
            _agg_functions[cid]->add(dst_row->agg_places(cid),
321
0
                                     const_cast<const doris::vectorized::IColumn**>(&col_ptr),
322
0
                                     src_row->_row_pos, _arena);
323
0
        }
324
    } else {
325
        DCHECK(_skip_bitmap_col_idx != -1);
326
        DCHECK_LT(_skip_bitmap_col_idx, mutable_block.columns());
327
        const BitmapValue& skip_bitmap =
328
                assert_cast<vectorized::ColumnBitmap*, TypeCheckOnRelease::DISABLE>(
329
                        mutable_block.mutable_columns()[_skip_bitmap_col_idx].get())
330
                        ->get_data()[src_row->_row_pos];
331
        for (size_t cid = _tablet_schema->num_key_columns(); cid < _num_columns; ++cid) {
332
            const auto& col = _tablet_schema->column(cid);
333
            if (cid != _skip_bitmap_col_idx && skip_bitmap.contains(col.unique_id())) {
334
                continue;
335
            }
336
            auto* col_ptr = mutable_block.mutable_columns()[cid].get();
337
            _agg_functions[cid]->add(dst_row->agg_places(cid),
338
                                     const_cast<const doris::vectorized::IColumn**>(&col_ptr),
339
                                     src_row->_row_pos, _arena);
340
        }
341
    }
342
0
}
Unexecuted instantiation: _ZN5doris8MemTable27_aggregate_two_row_in_blockILb1EEEvRNS_10vectorized12MutableBlockEPNS_10RowInBlockES6_
343
9
Status MemTable::_put_into_output(vectorized::Block& in_block) {
344
9
    SCOPED_RAW_TIMER(&_stat.put_into_output_ns);
345
9
    DorisVector<uint32_t> row_pos_vec;
346
9
    DCHECK(in_block.rows() <= std::numeric_limits<int>::max());
347
9
    row_pos_vec.reserve(in_block.rows());
348
20
    for (int i = 0; i < _row_in_blocks->size(); i++) {
349
11
        row_pos_vec.emplace_back((*_row_in_blocks)[i]->_row_pos);
350
11
    }
351
9
    return _output_mutable_block.add_rows(&in_block, row_pos_vec.data(),
352
9
                                          row_pos_vec.data() + in_block.rows());
353
9
}
354
355
12
size_t MemTable::_sort() {
356
12
    SCOPED_RAW_TIMER(&_stat.sort_ns);
357
12
    _stat.sort_times++;
358
12
    size_t same_keys_num = 0;
359
    // sort new rows
360
12
    Tie tie = Tie(_last_sorted_pos, _row_in_blocks->size());
361
43
    for (size_t i = 0; i < _tablet_schema->num_key_columns(); i++) {
362
31
        auto cmp = [&](RowInBlock* lhs, RowInBlock* rhs) -> int {
363
30
            return _input_mutable_block.compare_one_column(lhs->_row_pos, rhs->_row_pos, i, -1);
364
30
        };
365
31
        _sort_one_column(*_row_in_blocks, tie, cmp);
366
31
    }
367
12
    bool is_dup = (_keys_type == KeysType::DUP_KEYS);
368
    // sort extra round by _row_pos to make the sort stable
369
12
    auto iter = tie.iter();
370
15
    while (iter.next()) {
371
3
        pdqsort(std::next(_row_in_blocks->begin(), iter.left()),
372
3
                std::next(_row_in_blocks->begin(), iter.right()),
373
3
                [&is_dup](const std::shared_ptr<RowInBlock>& lhs,
374
3
                          const std::shared_ptr<RowInBlock>& rhs) -> bool {
375
3
                    return is_dup ? lhs->_row_pos > rhs->_row_pos : lhs->_row_pos < rhs->_row_pos;
376
3
                });
377
3
        same_keys_num += iter.right() - iter.left();
378
3
    }
379
    // merge new rows and old rows
380
12
    _vec_row_comparator->set_block(&_input_mutable_block);
381
12
    auto cmp_func = [this, is_dup, &same_keys_num](const std::shared_ptr<RowInBlock>& l,
382
12
                                                   const std::shared_ptr<RowInBlock>& r) -> bool {
383
0
        auto value = (*(this->_vec_row_comparator))(l.get(), r.get());
384
0
        if (value == 0) {
385
0
            same_keys_num++;
386
0
            return is_dup ? l->_row_pos > r->_row_pos : l->_row_pos < r->_row_pos;
387
0
        } else {
388
0
            return value < 0;
389
0
        }
390
0
    };
391
12
    auto new_row_it = std::next(_row_in_blocks->begin(), _last_sorted_pos);
392
12
    std::inplace_merge(_row_in_blocks->begin(), new_row_it, _row_in_blocks->end(), cmp_func);
393
12
    _last_sorted_pos = _row_in_blocks->size();
394
12
    return same_keys_num;
395
12
}
396
397
1
Status MemTable::_sort_by_cluster_keys() {
398
1
    SCOPED_RAW_TIMER(&_stat.sort_ns);
399
1
    _stat.sort_times++;
400
    // sort all rows
401
1
    vectorized::Block in_block = _output_mutable_block.to_block();
402
1
    vectorized::MutableBlock mutable_block =
403
1
            vectorized::MutableBlock::build_mutable_block(&in_block);
404
1
    auto clone_block = in_block.clone_without_columns();
405
1
    _output_mutable_block = vectorized::MutableBlock::build_mutable_block(&clone_block);
406
407
1
    DorisVector<std::shared_ptr<RowInBlock>> row_in_blocks;
408
1
    row_in_blocks.reserve(mutable_block.rows());
409
5
    for (size_t i = 0; i < mutable_block.rows(); i++) {
410
4
        row_in_blocks.emplace_back(std::make_shared<RowInBlock>(i));
411
4
    }
412
1
    Tie tie = Tie(0, mutable_block.rows());
413
414
2
    for (auto cid : _tablet_schema->cluster_key_uids()) {
415
2
        auto index = _tablet_schema->field_index(cid);
416
2
        if (index == -1) {
417
0
            return Status::InternalError("could not find cluster key column with unique_id=" +
418
0
                                         std::to_string(cid) + " in tablet schema");
419
0
        }
420
8
        auto cmp = [&](const RowInBlock* lhs, const RowInBlock* rhs) -> int {
421
8
            return mutable_block.compare_one_column(lhs->_row_pos, rhs->_row_pos, index, -1);
422
8
        };
423
2
        _sort_one_column(row_in_blocks, tie, cmp);
424
2
    }
425
426
    // sort extra round by _row_pos to make the sort stable
427
1
    auto iter = tie.iter();
428
1
    while (iter.next()) {
429
0
        pdqsort(std::next(row_in_blocks.begin(), iter.left()),
430
0
                std::next(row_in_blocks.begin(), iter.right()),
431
0
                [](const std::shared_ptr<RowInBlock>& lhs, const std::shared_ptr<RowInBlock>& rhs)
432
0
                        -> bool { return lhs->_row_pos < rhs->_row_pos; });
433
0
    }
434
435
1
    in_block = mutable_block.to_block();
436
1
    SCOPED_RAW_TIMER(&_stat.put_into_output_ns);
437
1
    DorisVector<uint32_t> row_pos_vec;
438
1
    DCHECK(in_block.rows() <= std::numeric_limits<int>::max());
439
1
    row_pos_vec.reserve(in_block.rows());
440
5
    for (int i = 0; i < row_in_blocks.size(); i++) {
441
4
        row_pos_vec.emplace_back(row_in_blocks[i]->_row_pos);
442
4
    }
443
1
    std::vector<int> column_offset;
444
6
    for (int i = 0; i < _column_offset.size(); ++i) {
445
5
        column_offset.emplace_back(i);
446
5
    }
447
1
    return _output_mutable_block.add_rows(&in_block, row_pos_vec.data(),
448
1
                                          row_pos_vec.data() + in_block.rows(), &column_offset);
449
1
}
450
451
void MemTable::_sort_one_column(DorisVector<std::shared_ptr<RowInBlock>>& row_in_blocks, Tie& tie,
452
33
                                std::function<int(RowInBlock*, RowInBlock*)> cmp) {
453
33
    auto iter = tie.iter();
454
43
    while (iter.next()) {
455
10
        pdqsort(std::next(row_in_blocks.begin(), static_cast<int>(iter.left())),
456
10
                std::next(row_in_blocks.begin(), static_cast<int>(iter.right())),
457
21
                [&cmp](auto lhs, auto rhs) -> bool { return cmp(lhs.get(), rhs.get()) < 0; });
458
10
        tie[iter.left()] = 0;
459
27
        for (auto i = iter.left() + 1; i < iter.right(); i++) {
460
17
            tie[i] = (cmp(row_in_blocks[i - 1].get(), row_in_blocks[i].get()) == 0);
461
17
        }
462
10
    }
463
33
}
464
465
template <bool is_final>
466
void MemTable::_finalize_one_row(RowInBlock* row,
467
                                 const vectorized::ColumnsWithTypeAndName& block_data,
468
6
                                 int row_pos) {
469
    // move key columns
470
18
    for (size_t i = 0; i < _tablet_schema->num_key_columns(); ++i) {
471
12
        _output_mutable_block.get_column_by_position(i)->insert_from(*block_data[i].column.get(),
472
12
                                                                     row->_row_pos);
473
12
    }
474
6
    if (row->has_init_agg()) {
475
        // get value columns from agg_places
476
12
        for (size_t i = _tablet_schema->num_key_columns(); i < _num_columns; ++i) {
477
9
            auto function = _agg_functions[i];
478
9
            auto* agg_place = row->agg_places(i);
479
9
            auto* col_ptr = _output_mutable_block.get_column_by_position(i).get();
480
9
            function->insert_result_into(agg_place, *col_ptr);
481
482
9
            if constexpr (is_final) {
483
9
                function->destroy(agg_place);
484
9
            } else {
485
0
                function->reset(agg_place);
486
0
            }
487
9
        }
488
489
3
        if constexpr (is_final) {
490
3
            row->remove_init_agg();
491
3
        } else {
492
0
            for (size_t i = _tablet_schema->num_key_columns(); i < _num_columns; ++i) {
493
0
                auto function = _agg_functions[i];
494
0
                auto* agg_place = row->agg_places(i);
495
0
                auto* col_ptr = _output_mutable_block.get_column_by_position(i).get();
496
0
                function->add(agg_place, const_cast<const doris::vectorized::IColumn**>(&col_ptr),
497
0
                              row_pos, _arena);
498
0
            }
499
0
        }
500
3
    } else {
501
        // move columns for rows do not need agg
502
12
        for (size_t i = _tablet_schema->num_key_columns(); i < _num_columns; ++i) {
503
9
            _output_mutable_block.get_column_by_position(i)->insert_from(
504
9
                    *block_data[i].column.get(), row->_row_pos);
505
9
        }
506
3
    }
507
6
    if constexpr (!is_final) {
508
0
        row->_row_pos = row_pos;
509
0
    }
510
6
}
Unexecuted instantiation: _ZN5doris8MemTable17_finalize_one_rowILb0EEEvPNS_10RowInBlockERKSt6vectorINS_10vectorized21ColumnWithTypeAndNameESaIS6_EEi
_ZN5doris8MemTable17_finalize_one_rowILb1EEEvPNS_10RowInBlockERKSt6vectorINS_10vectorized21ColumnWithTypeAndNameESaIS6_EEi
Line
Count
Source
468
6
                                 int row_pos) {
469
    // move key columns
470
18
    for (size_t i = 0; i < _tablet_schema->num_key_columns(); ++i) {
471
12
        _output_mutable_block.get_column_by_position(i)->insert_from(*block_data[i].column.get(),
472
12
                                                                     row->_row_pos);
473
12
    }
474
6
    if (row->has_init_agg()) {
475
        // get value columns from agg_places
476
12
        for (size_t i = _tablet_schema->num_key_columns(); i < _num_columns; ++i) {
477
9
            auto function = _agg_functions[i];
478
9
            auto* agg_place = row->agg_places(i);
479
9
            auto* col_ptr = _output_mutable_block.get_column_by_position(i).get();
480
9
            function->insert_result_into(agg_place, *col_ptr);
481
482
9
            if constexpr (is_final) {
483
9
                function->destroy(agg_place);
484
            } else {
485
                function->reset(agg_place);
486
            }
487
9
        }
488
489
3
        if constexpr (is_final) {
490
3
            row->remove_init_agg();
491
        } else {
492
            for (size_t i = _tablet_schema->num_key_columns(); i < _num_columns; ++i) {
493
                auto function = _agg_functions[i];
494
                auto* agg_place = row->agg_places(i);
495
                auto* col_ptr = _output_mutable_block.get_column_by_position(i).get();
496
                function->add(agg_place, const_cast<const doris::vectorized::IColumn**>(&col_ptr),
497
                              row_pos, _arena);
498
            }
499
        }
500
3
    } else {
501
        // move columns for rows do not need agg
502
12
        for (size_t i = _tablet_schema->num_key_columns(); i < _num_columns; ++i) {
503
9
            _output_mutable_block.get_column_by_position(i)->insert_from(
504
9
                    *block_data[i].column.get(), row->_row_pos);
505
9
        }
506
3
    }
507
    if constexpr (!is_final) {
508
        row->_row_pos = row_pos;
509
    }
510
6
}
511
512
3
void MemTable::_init_row_for_agg(RowInBlock* row, vectorized::MutableBlock& mutable_block) {
513
3
    row->init_agg_places(_arena.aligned_alloc(_total_size_of_aggregate_states, 16),
514
3
                         _offsets_of_aggregate_states.data());
515
12
    for (auto cid = _tablet_schema->num_key_columns(); cid < _num_columns; cid++) {
516
9
        auto* col_ptr = mutable_block.mutable_columns()[cid].get();
517
9
        auto* data = row->agg_places(cid);
518
9
        _agg_functions[cid]->create(data);
519
9
        _agg_functions[cid]->add(data, const_cast<const doris::vectorized::IColumn**>(&col_ptr),
520
9
                                 row->_row_pos, _arena);
521
9
    }
522
3
}
523
3
void MemTable::_clear_row_agg(RowInBlock* row) {
524
3
    if (row->has_init_agg()) {
525
0
        for (size_t i = _tablet_schema->num_key_columns(); i < _num_columns; ++i) {
526
0
            auto function = _agg_functions[i];
527
0
            auto* agg_place = row->agg_places(i);
528
0
            function->destroy(agg_place);
529
0
        }
530
0
        row->remove_init_agg();
531
0
    }
532
3
}
533
// only in `to_block` the `is_final` flag will be true, in other cases, it will be false
534
template <bool is_final, bool has_skip_bitmap_col>
535
3
void MemTable::_aggregate() {
536
3
    SCOPED_RAW_TIMER(&_stat.agg_ns);
537
3
    _stat.agg_times++;
538
3
    vectorized::Block in_block = _input_mutable_block.to_block();
539
3
    vectorized::MutableBlock mutable_block =
540
3
            vectorized::MutableBlock::build_mutable_block(&in_block);
541
3
    _vec_row_comparator->set_block(&mutable_block);
542
3
    auto& block_data = in_block.get_columns_with_type_and_name();
543
3
    DorisVector<std::shared_ptr<RowInBlock>> temp_row_in_blocks;
544
3
    temp_row_in_blocks.reserve(_last_sorted_pos);
545
    //only init agg if needed
546
547
3
    if constexpr (!has_skip_bitmap_col) {
548
3
        RowInBlock* prev_row = nullptr;
549
3
        int row_pos = -1;
550
9
        for (const auto& cur_row_ptr : *_row_in_blocks) {
551
9
            RowInBlock* cur_row = cur_row_ptr.get();
552
9
            if (!temp_row_in_blocks.empty() && (*_vec_row_comparator)(prev_row, cur_row) == 0) {
553
3
                if (!prev_row->has_init_agg()) {
554
3
                    _init_row_for_agg(prev_row, mutable_block);
555
3
                }
556
3
                _stat.merged_rows++;
557
3
                if (_tablet_schema->has_seq_map()) {
558
0
                    _aggregate_two_row_with_sequence_map(mutable_block, cur_row, prev_row);
559
3
                } else {
560
3
                    _aggregate_two_row_in_block<has_skip_bitmap_col>(mutable_block, cur_row,
561
3
                                                                     prev_row);
562
3
                }
563
564
                // Clean up aggregation state of the merged row to avoid memory leak
565
3
                if (cur_row) {
566
3
                    _clear_row_agg(cur_row);
567
3
                }
568
6
            } else {
569
6
                prev_row = cur_row;
570
6
                if (!temp_row_in_blocks.empty()) {
571
                    // The rows from the previous batch of _row_in_blocks have been merged into temp_row_in_blocks,
572
                    // now call finalize to write the aggregation results into _output_mutable_block.
573
3
                    _finalize_one_row<is_final>(temp_row_in_blocks.back().get(), block_data,
574
3
                                                row_pos);
575
3
                }
576
6
                temp_row_in_blocks.push_back(cur_row_ptr);
577
6
                row_pos++;
578
6
            }
579
9
        }
580
3
        if (!temp_row_in_blocks.empty()) {
581
            // finalize the last low
582
3
            _finalize_one_row<is_final>(temp_row_in_blocks.back().get(), block_data, row_pos);
583
3
        }
584
3
    } else {
585
0
        DCHECK(_delete_sign_col_idx != -1);
586
0
        if (_seq_col_idx_in_block == -1) {
587
0
            _aggregate_for_flexible_partial_update_without_seq_col<is_final>(
588
0
                    block_data, mutable_block, temp_row_in_blocks);
589
0
        } else {
590
0
            _aggregate_for_flexible_partial_update_with_seq_col<is_final>(block_data, mutable_block,
591
0
                                                                          temp_row_in_blocks);
592
0
        }
593
0
    }
594
3
    if constexpr (!is_final) {
595
        // if is not final, we collect the agg results to input_block and then continue to insert
596
0
        _input_mutable_block.swap(_output_mutable_block);
597
        //TODO(weixang):opt here.
598
0
        std::unique_ptr<vectorized::Block> empty_input_block = in_block.create_same_struct_block(0);
599
0
        _output_mutable_block =
600
0
                vectorized::MutableBlock::build_mutable_block(empty_input_block.get());
601
0
        _output_mutable_block.clear_column_data();
602
0
        *_row_in_blocks = temp_row_in_blocks;
603
0
        _last_sorted_pos = _row_in_blocks->size();
604
0
    }
605
3
}
Unexecuted instantiation: _ZN5doris8MemTable10_aggregateILb0ELb0EEEvv
Unexecuted instantiation: _ZN5doris8MemTable10_aggregateILb0ELb1EEEvv
_ZN5doris8MemTable10_aggregateILb1ELb0EEEvv
Line
Count
Source
535
3
void MemTable::_aggregate() {
536
3
    SCOPED_RAW_TIMER(&_stat.agg_ns);
537
3
    _stat.agg_times++;
538
3
    vectorized::Block in_block = _input_mutable_block.to_block();
539
3
    vectorized::MutableBlock mutable_block =
540
3
            vectorized::MutableBlock::build_mutable_block(&in_block);
541
3
    _vec_row_comparator->set_block(&mutable_block);
542
3
    auto& block_data = in_block.get_columns_with_type_and_name();
543
3
    DorisVector<std::shared_ptr<RowInBlock>> temp_row_in_blocks;
544
3
    temp_row_in_blocks.reserve(_last_sorted_pos);
545
    //only init agg if needed
546
547
3
    if constexpr (!has_skip_bitmap_col) {
548
3
        RowInBlock* prev_row = nullptr;
549
3
        int row_pos = -1;
550
9
        for (const auto& cur_row_ptr : *_row_in_blocks) {
551
9
            RowInBlock* cur_row = cur_row_ptr.get();
552
9
            if (!temp_row_in_blocks.empty() && (*_vec_row_comparator)(prev_row, cur_row) == 0) {
553
3
                if (!prev_row->has_init_agg()) {
554
3
                    _init_row_for_agg(prev_row, mutable_block);
555
3
                }
556
3
                _stat.merged_rows++;
557
3
                if (_tablet_schema->has_seq_map()) {
558
0
                    _aggregate_two_row_with_sequence_map(mutable_block, cur_row, prev_row);
559
3
                } else {
560
3
                    _aggregate_two_row_in_block<has_skip_bitmap_col>(mutable_block, cur_row,
561
3
                                                                     prev_row);
562
3
                }
563
564
                // Clean up aggregation state of the merged row to avoid memory leak
565
3
                if (cur_row) {
566
3
                    _clear_row_agg(cur_row);
567
3
                }
568
6
            } else {
569
6
                prev_row = cur_row;
570
6
                if (!temp_row_in_blocks.empty()) {
571
                    // The rows from the previous batch of _row_in_blocks have been merged into temp_row_in_blocks,
572
                    // now call finalize to write the aggregation results into _output_mutable_block.
573
3
                    _finalize_one_row<is_final>(temp_row_in_blocks.back().get(), block_data,
574
3
                                                row_pos);
575
3
                }
576
6
                temp_row_in_blocks.push_back(cur_row_ptr);
577
6
                row_pos++;
578
6
            }
579
9
        }
580
3
        if (!temp_row_in_blocks.empty()) {
581
            // finalize the last low
582
3
            _finalize_one_row<is_final>(temp_row_in_blocks.back().get(), block_data, row_pos);
583
3
        }
584
    } else {
585
        DCHECK(_delete_sign_col_idx != -1);
586
        if (_seq_col_idx_in_block == -1) {
587
            _aggregate_for_flexible_partial_update_without_seq_col<is_final>(
588
                    block_data, mutable_block, temp_row_in_blocks);
589
        } else {
590
            _aggregate_for_flexible_partial_update_with_seq_col<is_final>(block_data, mutable_block,
591
                                                                          temp_row_in_blocks);
592
        }
593
    }
594
    if constexpr (!is_final) {
595
        // if is not final, we collect the agg results to input_block and then continue to insert
596
        _input_mutable_block.swap(_output_mutable_block);
597
        //TODO(weixang):opt here.
598
        std::unique_ptr<vectorized::Block> empty_input_block = in_block.create_same_struct_block(0);
599
        _output_mutable_block =
600
                vectorized::MutableBlock::build_mutable_block(empty_input_block.get());
601
        _output_mutable_block.clear_column_data();
602
        *_row_in_blocks = temp_row_in_blocks;
603
        _last_sorted_pos = _row_in_blocks->size();
604
    }
605
3
}
Unexecuted instantiation: _ZN5doris8MemTable10_aggregateILb1ELb1EEEvv
606
607
template <bool is_final>
608
void MemTable::_aggregate_for_flexible_partial_update_without_seq_col(
609
        const vectorized::ColumnsWithTypeAndName& block_data,
610
        vectorized::MutableBlock& mutable_block,
611
0
        DorisVector<std::shared_ptr<RowInBlock>>& temp_row_in_blocks) {
612
0
    std::shared_ptr<RowInBlock> prev_row {nullptr};
613
0
    int row_pos = -1;
614
0
    auto& skip_bitmaps = assert_cast<vectorized::ColumnBitmap*>(
615
0
                                 mutable_block.mutable_columns()[_skip_bitmap_col_idx].get())
616
0
                                 ->get_data();
617
0
    auto& delete_signs = assert_cast<vectorized::ColumnInt8*>(
618
0
                                 mutable_block.mutable_columns()[_delete_sign_col_idx].get())
619
0
                                 ->get_data();
620
0
    std::shared_ptr<RowInBlock> row_with_delete_sign {nullptr};
621
0
    std::shared_ptr<RowInBlock> row_without_delete_sign {nullptr};
622
623
0
    auto finalize_rows = [&]() {
624
0
        if (row_with_delete_sign != nullptr) {
625
0
            temp_row_in_blocks.push_back(row_with_delete_sign);
626
0
            _finalize_one_row<is_final>(row_with_delete_sign.get(), block_data, ++row_pos);
627
0
            row_with_delete_sign = nullptr;
628
0
        }
629
0
        if (row_without_delete_sign != nullptr) {
630
0
            temp_row_in_blocks.push_back(row_without_delete_sign);
631
0
            _finalize_one_row<is_final>(row_without_delete_sign.get(), block_data, ++row_pos);
632
0
            row_without_delete_sign = nullptr;
633
0
        }
634
        // _arena.clear();
635
0
    };
Unexecuted instantiation: _ZZN5doris8MemTable54_aggregate_for_flexible_partial_update_without_seq_colILb0EEEvRKSt6vectorINS_10vectorized21ColumnWithTypeAndNameESaIS4_EERNS3_12MutableBlockERS2_ISt10shared_ptrINS_10RowInBlockEENS_18CustomStdAllocatorISD_NS_9AllocatorILb0ELb0ELb0ENS_22DefaultMemoryAllocatorELb1EEEEEEENKUlvE_clEv
Unexecuted instantiation: _ZZN5doris8MemTable54_aggregate_for_flexible_partial_update_without_seq_colILb1EEEvRKSt6vectorINS_10vectorized21ColumnWithTypeAndNameESaIS4_EERNS3_12MutableBlockERS2_ISt10shared_ptrINS_10RowInBlockEENS_18CustomStdAllocatorISD_NS_9AllocatorILb0ELb0ELb0ENS_22DefaultMemoryAllocatorELb1EEEEEEENKUlvE_clEv
636
637
0
    auto add_row = [&](std::shared_ptr<RowInBlock> row, bool with_delete_sign) {
638
0
        if (with_delete_sign) {
639
0
            row_with_delete_sign = std::move(row);
640
0
        } else {
641
0
            row_without_delete_sign = std::move(row);
642
0
        }
643
0
    };
Unexecuted instantiation: _ZZN5doris8MemTable54_aggregate_for_flexible_partial_update_without_seq_colILb0EEEvRKSt6vectorINS_10vectorized21ColumnWithTypeAndNameESaIS4_EERNS3_12MutableBlockERS2_ISt10shared_ptrINS_10RowInBlockEENS_18CustomStdAllocatorISD_NS_9AllocatorILb0ELb0ELb0ENS_22DefaultMemoryAllocatorELb1EEEEEEENKUlSD_bE_clESD_b
Unexecuted instantiation: _ZZN5doris8MemTable54_aggregate_for_flexible_partial_update_without_seq_colILb1EEEvRKSt6vectorINS_10vectorized21ColumnWithTypeAndNameESaIS4_EERNS3_12MutableBlockERS2_ISt10shared_ptrINS_10RowInBlockEENS_18CustomStdAllocatorISD_NS_9AllocatorILb0ELb0ELb0ENS_22DefaultMemoryAllocatorELb1EEEEEEENKUlSD_bE_clESD_b
644
0
    for (const auto& cur_row_ptr : *_row_in_blocks) {
645
0
        RowInBlock* cur_row = cur_row_ptr.get();
646
0
        const BitmapValue& skip_bitmap = skip_bitmaps[cur_row->_row_pos];
647
0
        bool cur_row_has_delete_sign = (!skip_bitmap.contains(_delete_sign_col_unique_id) &&
648
0
                                        delete_signs[cur_row->_row_pos] != 0);
649
0
        prev_row =
650
0
                (row_with_delete_sign == nullptr) ? row_without_delete_sign : row_with_delete_sign;
651
        // compare keys, the keys of row_with_delete_sign and row_without_delete_sign is the same,
652
        // choose any of them if it's valid
653
0
        if (prev_row != nullptr && (*_vec_row_comparator)(prev_row.get(), cur_row) == 0) {
654
0
            if (cur_row_has_delete_sign) {
655
0
                if (row_without_delete_sign != nullptr) {
656
                    // if there exits row without delete sign, remove it first
657
0
                    _clear_row_agg(row_without_delete_sign.get());
658
0
                    _stat.merged_rows++;
659
0
                    row_without_delete_sign = nullptr;
660
0
                }
661
                // and then unconditionally replace the previous row
662
0
                prev_row = row_with_delete_sign;
663
0
            } else {
664
0
                prev_row = row_without_delete_sign;
665
0
            }
666
667
0
            if (prev_row == nullptr) {
668
0
                add_row(cur_row_ptr, cur_row_has_delete_sign);
669
0
            } else {
670
0
                if (!prev_row->has_init_agg()) {
671
0
                    _init_row_for_agg(prev_row.get(), mutable_block);
672
0
                }
673
0
                _stat.merged_rows++;
674
0
                _aggregate_two_row_in_block<true>(mutable_block, cur_row, prev_row.get());
675
0
            }
676
0
        } else {
677
0
            finalize_rows();
678
0
            add_row(cur_row_ptr, cur_row_has_delete_sign);
679
0
        }
680
0
    }
681
    // finalize the last lows
682
0
    finalize_rows();
683
0
}
Unexecuted instantiation: _ZN5doris8MemTable54_aggregate_for_flexible_partial_update_without_seq_colILb0EEEvRKSt6vectorINS_10vectorized21ColumnWithTypeAndNameESaIS4_EERNS3_12MutableBlockERS2_ISt10shared_ptrINS_10RowInBlockEENS_18CustomStdAllocatorISD_NS_9AllocatorILb0ELb0ELb0ENS_22DefaultMemoryAllocatorELb1EEEEEE
Unexecuted instantiation: _ZN5doris8MemTable54_aggregate_for_flexible_partial_update_without_seq_colILb1EEEvRKSt6vectorINS_10vectorized21ColumnWithTypeAndNameESaIS4_EERNS3_12MutableBlockERS2_ISt10shared_ptrINS_10RowInBlockEENS_18CustomStdAllocatorISD_NS_9AllocatorILb0ELb0ELb0ENS_22DefaultMemoryAllocatorELb1EEEEEE
684
685
template <bool is_final>
686
void MemTable::_aggregate_for_flexible_partial_update_with_seq_col(
687
        const vectorized::ColumnsWithTypeAndName& block_data,
688
        vectorized::MutableBlock& mutable_block,
689
0
        DorisVector<std::shared_ptr<RowInBlock>>& temp_row_in_blocks) {
690
    // For flexible partial update, when table has sequence column, we don't do any aggregation
691
    // in memtable. These duplicate rows will be aggregated in VerticalSegmentWriter
692
0
    int row_pos = -1;
693
0
    for (const auto& row_ptr : *_row_in_blocks) {
694
0
        RowInBlock* row = row_ptr.get();
695
0
        temp_row_in_blocks.push_back(row_ptr);
696
0
        _finalize_one_row<is_final>(row, block_data, ++row_pos);
697
0
    }
698
0
}
Unexecuted instantiation: _ZN5doris8MemTable51_aggregate_for_flexible_partial_update_with_seq_colILb0EEEvRKSt6vectorINS_10vectorized21ColumnWithTypeAndNameESaIS4_EERNS3_12MutableBlockERS2_ISt10shared_ptrINS_10RowInBlockEENS_18CustomStdAllocatorISD_NS_9AllocatorILb0ELb0ELb0ENS_22DefaultMemoryAllocatorELb1EEEEEE
Unexecuted instantiation: _ZN5doris8MemTable51_aggregate_for_flexible_partial_update_with_seq_colILb1EEEvRKSt6vectorINS_10vectorized21ColumnWithTypeAndNameESaIS4_EERNS3_12MutableBlockERS2_ISt10shared_ptrINS_10RowInBlockEENS_18CustomStdAllocatorISD_NS_9AllocatorILb0ELb0ELb0ENS_22DefaultMemoryAllocatorELb1EEEEEE
699
700
0
void MemTable::shrink_memtable_by_agg() {
701
0
    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(
702
0
            _resource_ctx->memory_context()->mem_tracker()->write_tracker());
703
0
    SCOPED_CONSUME_MEM_TRACKER(_mem_tracker);
704
0
    if (_keys_type == KeysType::DUP_KEYS) {
705
0
        return;
706
0
    }
707
0
    size_t same_keys_num = _sort();
708
0
    if (same_keys_num != 0) {
709
0
        (_skip_bitmap_col_idx == -1) ? _aggregate<false, false>() : _aggregate<false, true>();
710
0
    }
711
0
    _last_agg_pos = memory_usage();
712
0
}
713
714
20
bool MemTable::need_flush() const {
715
20
    DBUG_EXECUTE_IF("MemTable.need_flush", { return true; });
716
717
    // If rows_of_segment is set in table properties, prioritize row-based flush
718
20
    if (_rows_of_segment > 0 && _stat.raw_rows.load() >= _rows_of_segment) {
719
0
        return true;
720
20
    } else {
721
20
        LOG_INFO("Do not flush memtable because rows_of_segment is not set or not reached")
722
20
                .tag("tablet_id", _tablet_id)
723
20
                .tag("rows_of_segment", _rows_of_segment)
724
20
                .tag("current_rows", _stat.raw_rows.load());
725
20
    }
726
727
20
    auto max_size = _adaptive_write_buffer_size();
728
20
    if (_partial_update_mode == UniqueKeyUpdateModePB::UPDATE_FIXED_COLUMNS) {
729
0
        auto update_columns_size = _num_columns;
730
0
        auto min_buffer_size = config::min_write_buffer_size_for_partial_update;
731
0
        max_size = max_size * update_columns_size / _tablet_schema->num_columns();
732
0
        max_size = max_size > min_buffer_size ? max_size : min_buffer_size;
733
0
    }
734
735
20
    if (memory_usage() >= max_size) {
736
0
        g_flush_cuz_memtable_full << 1;
737
0
        return true;
738
0
    }
739
20
    return false;
740
20
}
741
742
20
int64_t MemTable::_adaptive_write_buffer_size() const {
743
20
    if (!config::enable_adaptive_write_buffer_size) [[unlikely]] {
744
0
        return config::write_buffer_size;
745
0
    }
746
20
    const int64_t current_load_mem_value = MemoryProfile::load_current_usage();
747
20
    int64_t factor = 4;
748
    // Memory usage intervals:
749
    // (80 %, 100 %] → 1× buffer
750
    // (50 %, 80 %]  → 2× buffer
751
    // [0 %, 50 %]   → 4× buffer
752
20
    if (current_load_mem_value > (_load_mem_limit * 4) / 5) { // > 80 %
753
0
        factor = 1;
754
20
    } else if (current_load_mem_value > _load_mem_limit / 2) { // > 50 %
755
0
        factor = 2;
756
0
    }
757
20
    return config::write_buffer_size * factor;
758
20
}
759
760
20
bool MemTable::need_agg() const {
761
20
    if (_keys_type == KeysType::AGG_KEYS) {
762
5
        auto max_size = _last_agg_pos + config::write_buffer_size_for_agg;
763
5
        return memory_usage() >= max_size;
764
5
    }
765
15
    return false;
766
20
}
767
768
12
size_t MemTable::get_flush_reserve_memory_size() const {
769
12
    if (_keys_type == KeysType::DUP_KEYS && _tablet_schema->num_key_columns() == 0) {
770
0
        return 0; // no need to reserve
771
0
    }
772
12
    return static_cast<size_t>(static_cast<double>(_input_mutable_block.allocated_bytes()) * 1.2);
773
12
}
774
775
12
Status MemTable::_to_block(std::unique_ptr<vectorized::Block>* res) {
776
12
    size_t same_keys_num = _sort();
777
12
    if (_keys_type == KeysType::DUP_KEYS || same_keys_num == 0) {
778
9
        if (_keys_type == KeysType::DUP_KEYS && _tablet_schema->num_key_columns() == 0) {
779
0
            _output_mutable_block.swap(_input_mutable_block);
780
9
        } else {
781
9
            vectorized::Block in_block = _input_mutable_block.to_block();
782
9
            RETURN_IF_ERROR(_put_into_output(in_block));
783
9
        }
784
9
    } else {
785
3
        (_skip_bitmap_col_idx == -1) ? _aggregate<true, false>() : _aggregate<true, true>();
786
3
    }
787
12
    if (_keys_type == KeysType::UNIQUE_KEYS && _enable_unique_key_mow &&
788
12
        !_tablet_schema->cluster_key_uids().empty()) {
789
1
        if (_partial_update_mode != UniqueKeyUpdateModePB::UPSERT) {
790
0
            return Status::InternalError(
791
0
                    "Partial update for mow with cluster keys is not supported");
792
0
        }
793
1
        RETURN_IF_ERROR(_sort_by_cluster_keys());
794
1
    }
795
12
    _input_mutable_block.clear();
796
12
    *res = vectorized::Block::create_unique(_output_mutable_block.to_block());
797
12
    return Status::OK();
798
12
}
799
800
12
Status MemTable::to_block(std::unique_ptr<vectorized::Block>* res) {
801
12
    RETURN_IF_ERROR_OR_CATCH_EXCEPTION(_to_block(res));
802
12
    return Status::OK();
803
12
}
804
805
#include "common/compile_check_end.h"
806
} // namespace doris