Coverage Report

Created: 2026-04-10 12:12

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