Coverage Report

Created: 2025-06-23 17:53

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