Coverage Report

Created: 2026-06-24 19:24

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