Coverage Report

Created: 2026-04-10 04:10

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/storage/rowset_builder.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 "storage/rowset_builder.h"
19
20
#include <brpc/controller.h>
21
#include <fmt/format.h>
22
23
#include <filesystem>
24
#include <memory>
25
#include <ostream>
26
#include <string>
27
#include <utility>
28
29
// IWYU pragma: no_include <opentelemetry/common/threadlocal.h>
30
#include "common/compiler_util.h" // IWYU pragma: keep
31
#include "common/config.h"
32
#include "common/status.h"
33
#include "core/block/block.h"
34
#include "io/fs/file_system.h"
35
#include "io/fs/file_writer.h" // IWYU pragma: keep
36
#include "runtime/memory/global_memory_arbitrator.h"
37
#include "storage/delete/calc_delete_bitmap_executor.h"
38
#include "storage/olap_define.h"
39
#include "storage/partial_update_info.h"
40
#include "storage/rowset/beta_rowset.h"
41
#include "storage/rowset/beta_rowset_writer.h"
42
#include "storage/rowset/pending_rowset_helper.h"
43
#include "storage/rowset/rowset_meta.h"
44
#include "storage/rowset/rowset_meta_manager.h"
45
#include "storage/rowset/rowset_writer.h"
46
#include "storage/rowset/rowset_writer_context.h"
47
#include "storage/schema_change/schema_change.h"
48
#include "storage/storage_engine.h"
49
#include "storage/tablet/tablet_manager.h"
50
#include "storage/tablet/tablet_meta.h"
51
#include "storage/tablet/tablet_schema.h"
52
#include "storage/tablet_info.h"
53
#include "storage/txn/txn_manager.h"
54
#include "util/brpc_client_cache.h"
55
#include "util/brpc_closure.h"
56
#include "util/debug_points.h"
57
#include "util/mem_info.h"
58
#include "util/stopwatch.hpp"
59
#include "util/time.h"
60
#include "util/trace.h"
61
62
namespace doris {
63
using namespace ErrorCode;
64
65
BaseRowsetBuilder::BaseRowsetBuilder(const WriteRequest& req, RuntimeProfile* profile)
66
267k
        : _req(req), _tablet_schema(std::make_shared<TabletSchema>()) {
67
267k
    _init_profile(profile);
68
267k
}
69
70
RowsetBuilder::RowsetBuilder(StorageEngine& engine, const WriteRequest& req,
71
                             RuntimeProfile* profile)
72
513
        : BaseRowsetBuilder(req, profile), _engine(engine) {}
73
74
267k
void BaseRowsetBuilder::_init_profile(RuntimeProfile* profile) {
75
267k
    _profile = profile->create_child(fmt::format("RowsetBuilder {}", _req.tablet_id), true, true);
76
267k
    _build_rowset_timer = ADD_TIMER(_profile, "BuildRowsetTime");
77
267k
    _submit_delete_bitmap_timer = ADD_TIMER(_profile, "DeleteBitmapSubmitTime");
78
267k
    _wait_delete_bitmap_timer = ADD_TIMER(_profile, "DeleteBitmapWaitTime");
79
267k
}
80
81
0
void RowsetBuilder::_init_profile(RuntimeProfile* profile) {
82
0
    BaseRowsetBuilder::_init_profile(profile);
83
0
    _commit_txn_timer = ADD_TIMER(_profile, "CommitTxnTime");
84
0
}
85
86
267k
BaseRowsetBuilder::~BaseRowsetBuilder() {
87
267k
    if (!_is_init) {
88
95.1k
        return;
89
95.1k
    }
90
91
171k
    if (_calc_delete_bitmap_token != nullptr) {
92
171k
        _calc_delete_bitmap_token->cancel();
93
171k
    }
94
171k
}
95
96
513
RowsetBuilder::~RowsetBuilder() {
97
513
    if (_is_init && !_is_committed) {
98
5
        _garbage_collection();
99
5
    }
100
513
}
101
102
4.29k
Tablet* RowsetBuilder::tablet() {
103
4.29k
    return static_cast<Tablet*>(_tablet.get());
104
4.29k
}
105
106
0
TabletSharedPtr RowsetBuilder::tablet_sptr() {
107
0
    return std::static_pointer_cast<Tablet>(_tablet);
108
0
}
109
110
5
void RowsetBuilder::_garbage_collection() {
111
5
    Status rollback_status;
112
5
    TxnManager* txn_mgr = _engine.txn_manager();
113
5
    if (tablet() != nullptr) {
114
5
        rollback_status = txn_mgr->rollback_txn(_req.partition_id, *tablet(), _req.txn_id);
115
5
    }
116
    // has to check rollback status, because the rowset maybe committed in this thread and
117
    // published in another thread, then rollback will fail.
118
    // when rollback failed should not delete rowset
119
5
    if (rollback_status.ok()) {
120
5
        _engine.add_unused_rowset(_rowset);
121
5
    }
122
5
}
123
124
51.5k
Status BaseRowsetBuilder::init_mow_context(std::shared_ptr<MowContext>& mow_context) {
125
51.5k
    std::lock_guard<std::shared_mutex> lck(tablet()->get_header_lock());
126
51.5k
    _max_version_in_flush_phase = tablet()->max_version_unlocked();
127
51.5k
    std::vector<RowsetSharedPtr> rowset_ptrs;
128
    // tablet is under alter process. The delete bitmap will be calculated after conversion.
129
51.5k
    if (tablet()->tablet_state() == TABLET_NOTREADY) {
130
        // Disable 'partial_update' when the tablet is undergoing a 'schema changing process'
131
35
        if (_req.table_schema_param->is_partial_update()) {
132
0
            return Status::InternalError(
133
0
                    "Unable to do 'partial_update' when "
134
0
                    "the tablet is undergoing a 'schema changing process'");
135
0
        }
136
35
        _rowset_ids->clear();
137
51.5k
    } else {
138
51.5k
        RETURN_IF_ERROR(
139
51.5k
                tablet()->get_all_rs_id_unlocked(_max_version_in_flush_phase, _rowset_ids.get()));
140
51.5k
        rowset_ptrs = tablet()->get_rowset_by_ids(_rowset_ids.get());
141
51.5k
    }
142
51.5k
    _delete_bitmap = std::make_shared<DeleteBitmap>(tablet()->tablet_id());
143
51.5k
    mow_context = std::make_shared<MowContext>(_max_version_in_flush_phase, _req.txn_id,
144
51.5k
                                               _rowset_ids, rowset_ptrs, _delete_bitmap);
145
51.5k
    return Status::OK();
146
51.5k
}
147
148
452
Status RowsetBuilder::check_tablet_version_count() {
149
452
    auto max_version_config = _tablet->max_version_config();
150
452
    auto version_count = tablet()->version_count();
151
452
    DBUG_EXECUTE_IF("RowsetBuilder.check_tablet_version_count.too_many_version",
152
452
                    { version_count = INT_MAX; });
153
    // Trigger TOO MANY VERSION error first
154
452
    if (version_count > max_version_config) {
155
0
        return Status::Error<TOO_MANY_VERSION>(
156
0
                "failed to init rowset builder. version count: {}, exceed limit: {}, "
157
0
                "tablet: {}. Please reduce the frequency of loading data or adjust the "
158
0
                "max_tablet_version_num or time_series_max_tablet_version_num in be.conf to a "
159
0
                "larger value.",
160
0
                version_count, max_version_config, _tablet->tablet_id());
161
0
    }
162
    // (TODO Refrain) Maybe we can use a configurable param instead of hardcoded values '100'.
163
    // max_version_config must > 100, otherwise silent errors will occur.
164
452
    if ((!config::disable_auto_compaction &&
165
452
         !_tablet->tablet_meta()->tablet_schema()->disable_auto_compaction()) &&
166
452
        (version_count > max_version_config - 100) &&
167
452
        !GlobalMemoryArbitrator::is_exceed_soft_mem_limit(GB_EXCHANGE_BYTE)) {
168
        // Trigger compaction
169
0
        auto st = _engine.submit_compaction_task(
170
0
                tablet_sptr(), CompactionType::CUMULATIVE_COMPACTION, true, true, 2);
171
0
        if (!st.ok()) [[unlikely]] {
172
0
            LOG(WARNING) << "failed to trigger compaction, tablet_id=" << _tablet->tablet_id()
173
0
                         << " : " << st;
174
0
        }
175
0
    }
176
452
    return Status::OK();
177
452
}
178
179
452
Status RowsetBuilder::prepare_txn() {
180
452
    return tablet()->prepare_txn(_req.partition_id, _req.txn_id, _req.load_id, false);
181
452
}
182
183
453
Status RowsetBuilder::init() {
184
453
    _tablet = DORIS_TRY(_engine.get_tablet(_req.tablet_id));
185
452
    std::shared_ptr<MowContext> mow_context;
186
452
    if (_tablet->enable_unique_key_merge_on_write()) {
187
423
        RETURN_IF_ERROR(init_mow_context(mow_context));
188
423
    }
189
190
452
    RETURN_IF_ERROR(check_tablet_version_count());
191
192
452
    auto version_count = tablet()->version_count() + tablet()->stale_version_count();
193
452
    if (tablet()->avg_rs_meta_serialize_size() * version_count >
194
452
        config::tablet_meta_serialize_size_limit) {
195
0
        return Status::Error<TOO_MANY_VERSION>(
196
0
                "failed to init rowset builder. meta serialize size : {}, exceed limit: {}, "
197
0
                "tablet: {}. Please reduce the frequency of loading data or adjust the "
198
0
                "max_tablet_version_num in be.conf to a larger value.",
199
0
                tablet()->avg_rs_meta_serialize_size() * version_count,
200
0
                config::tablet_meta_serialize_size_limit, _tablet->tablet_id());
201
0
    }
202
203
452
    RETURN_IF_ERROR(prepare_txn());
204
205
452
    DBUG_EXECUTE_IF("BaseRowsetBuilder::init.check_partial_update_column_num", {
206
452
        if (_req.table_schema_param->partial_update_input_columns().size() !=
207
452
            dp->param<int>("column_num")) {
208
452
            return Status::InternalError("partial update input column num wrong!");
209
452
        };
210
452
    })
211
    // build tablet schema in request level
212
452
    RETURN_IF_ERROR(_build_current_tablet_schema(_req.index_id, _req.table_schema_param.get(),
213
452
                                                 *_tablet->tablet_schema()));
214
452
    RowsetWriterContext context;
215
452
    context.txn_id = _req.txn_id;
216
452
    context.load_id = _req.load_id;
217
452
    context.rowset_state = PREPARED;
218
452
    context.segments_overlap = OVERLAPPING;
219
452
    context.tablet_schema = _tablet_schema;
220
452
    context.newest_write_timestamp = UnixSeconds();
221
452
    context.tablet_id = _req.tablet_id;
222
452
    context.index_id = _req.index_id;
223
452
    context.tablet = _tablet;
224
452
    context.enable_segcompaction = true;
225
452
    context.write_type = DataWriteType::TYPE_DIRECT;
226
452
    context.mow_context = mow_context;
227
452
    context.write_file_cache = _req.write_file_cache;
228
452
    context.partial_update_info = _partial_update_info;
229
452
    _rowset_writer = DORIS_TRY(_tablet->create_rowset_writer(context, false));
230
452
    _pending_rs_guard = _engine.pending_local_rowsets().add(context.rowset_id);
231
232
452
    _calc_delete_bitmap_token = _engine.calc_delete_bitmap_executor()->create_token();
233
234
452
    _is_init = true;
235
452
    return Status::OK();
236
452
}
237
238
171k
Status BaseRowsetBuilder::build_rowset() {
239
171k
    std::lock_guard<std::mutex> l(_lock);
240
18.4E
    DCHECK(_is_init) << "rowset builder is supposed be to initialized before "
241
18.4E
                        "build_rowset() being called";
242
243
171k
    SCOPED_TIMER(_build_rowset_timer);
244
    // use rowset meta manager to save meta
245
171k
    RETURN_NOT_OK_STATUS_WITH_WARN(_rowset_writer->build(_rowset), "fail to build rowset");
246
171k
    return Status::OK();
247
171k
}
248
249
171k
Status BaseRowsetBuilder::submit_calc_delete_bitmap_task() {
250
171k
    if (!_tablet->enable_unique_key_merge_on_write() || _rowset->num_segments() == 0) {
251
150k
        return Status::OK();
252
150k
    }
253
20.9k
    std::lock_guard<std::mutex> l(_lock);
254
20.9k
    SCOPED_TIMER(_submit_delete_bitmap_timer);
255
20.9k
    if (_partial_update_info && _partial_update_info->is_flexible_partial_update()) {
256
264
        if (_rowset->num_segments() > 1) {
257
            // in flexible partial update, when there are more one segment in one load,
258
            // we need to do alignment process for same keys between segments, we haven't
259
            // implemented it yet and just report an error when encouter this situation
260
0
            return Status::NotSupported(
261
0
                    "too large input data in flexible partial update, Please "
262
0
                    "reduce the amount of data imported in a single load.");
263
0
        }
264
264
    }
265
266
20.9k
    auto* beta_rowset = reinterpret_cast<BetaRowset*>(_rowset.get());
267
20.9k
    std::vector<segment_v2::SegmentSharedPtr> segments;
268
20.9k
    RETURN_IF_ERROR(beta_rowset->load_segments(&segments));
269
20.9k
    if (segments.size() > 1) {
270
        // calculate delete bitmap between segments
271
0
        if (config::enable_calc_delete_bitmap_between_segments_concurrently) {
272
0
            RETURN_IF_ERROR(_calc_delete_bitmap_token->submit(
273
0
                    _tablet, _tablet_schema, _rowset->rowset_id(), segments, _delete_bitmap));
274
0
        } else {
275
0
            RETURN_IF_ERROR(_tablet->calc_delete_bitmap_between_segments(
276
0
                    _tablet_schema, _rowset->rowset_id(), segments, _delete_bitmap));
277
0
        }
278
0
    }
279
280
    // For partial update, we need to fill in the entire row of data, during the calculation
281
    // of the delete bitmap. This operation is resource-intensive, and we need to minimize
282
    // the number of times it occurs. Therefore, we skip this operation here.
283
20.9k
    if (_partial_update_info->is_partial_update()) {
284
        // for partial update, the delete bitmap calculation is done while append_block()
285
        // we print it's summarize logs here before commit.
286
1.47k
        LOG(INFO) << fmt::format(
287
1.47k
                "{} calc delete bitmap summary before commit: tablet({}), txn_id({}), "
288
1.47k
                "rowset_ids({}), cur max_version({}), bitmap num({}), bitmap_cardinality({}), num "
289
1.47k
                "rows updated({}), num rows new added({}), num rows deleted({}), total rows({})",
290
1.47k
                _partial_update_info->partial_update_mode_str(), tablet()->tablet_id(), _req.txn_id,
291
1.47k
                _rowset_ids->size(), rowset_writer()->context().mow_context->max_version,
292
1.47k
                _delete_bitmap->get_delete_bitmap_count(), _delete_bitmap->cardinality(),
293
1.47k
                rowset_writer()->num_rows_updated(), rowset_writer()->num_rows_new_added(),
294
1.47k
                rowset_writer()->num_rows_deleted(), rowset_writer()->num_rows());
295
1.47k
        return Status::OK();
296
1.47k
    }
297
298
20.9k
    LOG(INFO) << "submit calc delete bitmap task to executor, tablet_id: " << tablet()->tablet_id()
299
19.4k
              << ", txn_id: " << _req.txn_id;
300
19.4k
    return BaseTablet::commit_phase_update_delete_bitmap(_tablet, _rowset, *_rowset_ids,
301
19.4k
                                                         _delete_bitmap, segments, _req.txn_id,
302
19.4k
                                                         _calc_delete_bitmap_token.get(), nullptr);
303
20.9k
}
304
305
171k
Status BaseRowsetBuilder::wait_calc_delete_bitmap() {
306
171k
    if (!_tablet->enable_unique_key_merge_on_write() || _partial_update_info->is_partial_update()) {
307
123k
        return Status::OK();
308
123k
    }
309
48.4k
    std::lock_guard<std::mutex> l(_lock);
310
48.4k
    SCOPED_TIMER(_wait_delete_bitmap_timer);
311
48.4k
    RETURN_IF_ERROR(_calc_delete_bitmap_token->wait());
312
48.4k
    return Status::OK();
313
48.4k
}
314
315
447
Status RowsetBuilder::commit_txn() {
316
447
    if (tablet()->enable_unique_key_merge_on_write() &&
317
447
        config::enable_merge_on_write_correctness_check && _rowset->num_rows() != 0 &&
318
447
        tablet()->tablet_state() != TABLET_NOTREADY) {
319
143
        auto st = tablet()->check_delete_bitmap_correctness(
320
143
                _delete_bitmap, _rowset->end_version() - 1, _req.txn_id, *_rowset_ids);
321
143
        if (!st.ok()) {
322
0
            LOG(WARNING) << fmt::format(
323
0
                    "[tablet_id:{}][txn_id:{}][load_id:{}][partition_id:{}] "
324
0
                    "delete bitmap correctness check failed in commit phase!",
325
0
                    _req.tablet_id, _req.txn_id, UniqueId(_req.load_id).to_string(),
326
0
                    _req.partition_id);
327
0
            return st;
328
0
        }
329
143
    }
330
447
    std::lock_guard<std::mutex> l(_lock);
331
447
    SCOPED_TIMER(_commit_txn_timer);
332
333
    // Transfer ownership of `PendingRowsetGuard` to `TxnManager`
334
447
    Status res = _engine.txn_manager()->commit_txn(
335
447
            _req.partition_id, *tablet(), _req.txn_id, _req.load_id, _rowset,
336
447
            std::move(_pending_rs_guard), false, _partial_update_info);
337
338
447
    if (!res && !res.is<PUSH_TRANSACTION_ALREADY_EXIST>()) {
339
0
        LOG(WARNING) << "Failed to commit txn: " << _req.txn_id
340
0
                     << " for rowset: " << _rowset->rowset_id();
341
0
        return res;
342
0
    }
343
447
    if (_tablet->enable_unique_key_merge_on_write()) {
344
423
        _engine.txn_manager()->set_txn_related_delete_bitmap(
345
423
                _req.partition_id, _req.txn_id, tablet()->tablet_id(), tablet()->tablet_uid(), true,
346
423
                _delete_bitmap, *_rowset_ids, _partial_update_info);
347
423
    }
348
349
447
    _is_committed = true;
350
447
    return Status::OK();
351
447
}
352
353
0
Status BaseRowsetBuilder::cancel() {
354
0
    std::lock_guard<std::mutex> l(_lock);
355
0
    if (_is_cancelled) {
356
0
        return Status::OK();
357
0
    }
358
0
    if (_calc_delete_bitmap_token != nullptr) {
359
0
        _calc_delete_bitmap_token->cancel();
360
0
    }
361
0
    _is_cancelled = true;
362
0
    return Status::OK();
363
0
}
364
365
Status BaseRowsetBuilder::_build_current_tablet_schema(
366
        int64_t index_id, const OlapTableSchemaParam* table_schema_param,
367
170k
        const TabletSchema& ori_tablet_schema) {
368
    // find the right index id
369
170k
    int i = 0;
370
170k
    auto indexes = table_schema_param->indexes();
371
186k
    for (; i < indexes.size(); i++) {
372
186k
        if (indexes[i]->index_id == index_id) {
373
170k
            break;
374
170k
        }
375
186k
    }
376
170k
    if (!indexes.empty() && !indexes[i]->columns.empty() &&
377
170k
        indexes[i]->columns[0]->unique_id() >= 0) {
378
170k
        _tablet_schema->shawdow_copy_without_columns(ori_tablet_schema);
379
170k
        _tablet_schema->build_current_tablet_schema(
380
170k
                index_id, cast_set<int32_t>(table_schema_param->version()), indexes[i],
381
170k
                ori_tablet_schema);
382
170k
    } else {
383
467
        _tablet_schema->copy_from(ori_tablet_schema);
384
467
    }
385
170k
    if (_tablet_schema->schema_version() > ori_tablet_schema.schema_version()) {
386
        // After schema change, should include extracted column
387
        // For example: a table has two columns, k and v
388
        // After adding a column v2, the schema version increases, max_version_schema needs to be updated.
389
        // _tablet_schema includes k, v, and v2
390
        // if v is a variant, need to add the columns decomposed from the v to the _tablet_schema.
391
1.22k
        if (_tablet_schema->num_variant_columns() > 0) {
392
98
            TabletSchemaSPtr max_version_schema = std::make_shared<TabletSchema>();
393
98
            max_version_schema->copy_from(*_tablet_schema);
394
98
            max_version_schema->copy_extracted_columns(ori_tablet_schema);
395
98
            _tablet->update_max_version_schema(max_version_schema);
396
1.12k
        } else {
397
1.12k
            _tablet->update_max_version_schema(_tablet_schema);
398
1.12k
        }
399
1.22k
    }
400
401
170k
    _tablet_schema->set_table_id(table_schema_param->table_id());
402
170k
    _tablet_schema->set_db_id(table_schema_param->db_id());
403
170k
    if (table_schema_param->is_partial_update()) {
404
3.57k
        _tablet_schema->set_auto_increment_column(table_schema_param->auto_increment_coulumn());
405
3.57k
    }
406
    // set partial update columns info
407
170k
    _partial_update_info = std::make_shared<PartialUpdateInfo>();
408
170k
    RETURN_IF_ERROR(_partial_update_info->init(
409
170k
            tablet()->tablet_id(), _req.txn_id, *_tablet_schema,
410
170k
            table_schema_param->unique_key_update_mode(),
411
170k
            table_schema_param->partial_update_new_key_policy(),
412
170k
            table_schema_param->partial_update_input_columns(),
413
170k
            table_schema_param->is_strict_mode(), table_schema_param->timestamp_ms(),
414
170k
            table_schema_param->nano_seconds(), table_schema_param->timezone(),
415
170k
            table_schema_param->auto_increment_coulumn(),
416
170k
            table_schema_param->sequence_map_col_uid(), _max_version_in_flush_phase));
417
170k
    return Status::OK();
418
170k
}
419
} // namespace doris