Coverage Report

Created: 2026-04-24 15:41

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