Coverage Report

Created: 2026-03-14 13:34

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