Coverage Report

Created: 2026-06-01 15:57

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/group_rowset_writer.h"
43
#include "storage/rowset/pending_rowset_helper.h"
44
#include "storage/rowset/rowset_factory.h"
45
#include "storage/rowset/rowset_meta.h"
46
#include "storage/rowset/rowset_meta_manager.h"
47
#include "storage/rowset/rowset_writer.h"
48
#include "storage/rowset/rowset_writer_context.h"
49
#include "storage/schema_change/schema_change.h"
50
#include "storage/storage_engine.h"
51
#include "storage/tablet/tablet_manager.h"
52
#include "storage/tablet/tablet_meta.h"
53
#include "storage/tablet/tablet_schema.h"
54
#include "storage/tablet/tablet_schema_cache.h"
55
#include "storage/tablet_info.h"
56
#include "storage/txn/txn_manager.h"
57
#include "util/brpc_client_cache.h"
58
#include "util/brpc_closure.h"
59
#include "util/debug_points.h"
60
#include "util/mem_info.h"
61
#include "util/stopwatch.hpp"
62
#include "util/time.h"
63
#include "util/trace.h"
64
65
namespace doris {
66
using namespace ErrorCode;
67
68
BaseRowsetBuilder::BaseRowsetBuilder(const WriteRequest& req, RuntimeProfile* profile)
69
304k
        : _req(req), _tablet_schema(std::make_shared<TabletSchema>()) {
70
304k
    if (profile != nullptr) {
71
18.6k
        _init_profile(profile);
72
18.6k
    }
73
304k
}
74
75
RowsetBuilder::RowsetBuilder(StorageEngine& engine, const WriteRequest& req,
76
                             RuntimeProfile* profile)
77
37.6k
        : BaseRowsetBuilder(req, profile), _engine(engine) {}
78
79
RowBinlogRowsetBuilder::RowBinlogRowsetBuilder(StorageEngine& engine, const WriteRequest& req,
80
                                               RuntimeProfile* profile)
81
1
        : RowsetBuilder(engine, req, profile) {}
82
83
18.6k
void BaseRowsetBuilder::_init_profile(RuntimeProfile* profile) {
84
18.6k
    DCHECK(profile != nullptr);
85
18.6k
    if (_req.write_req_type == WriteRequestType::GROUP) {
86
1
        _profile = profile->create_child(fmt::format("GroupRowsetBuilder {}", _req.tablet_id), true,
87
1
                                         true);
88
1
        return;
89
1
    }
90
91
18.6k
    _profile = profile->create_child(
92
18.6k
            fmt::format(
93
18.6k
                    "RowsetBuilder {} {}", _req.tablet_id,
94
18.6k
                    _req.write_req_type == WriteRequestType::ROW_BINLOG ? "binlog<row>" : "data"),
95
18.6k
            true, true);
96
18.6k
    _build_rowset_timer = ADD_TIMER(_profile, "BuildRowsetTime");
97
18.6k
    _submit_delete_bitmap_timer = ADD_TIMER(_profile, "DeleteBitmapSubmitTime");
98
18.6k
    _wait_delete_bitmap_timer = ADD_TIMER(_profile, "DeleteBitmapWaitTime");
99
18.6k
}
100
101
0
void RowsetBuilder::_init_profile(RuntimeProfile* profile) {
102
0
    DCHECK(profile != nullptr);
103
0
    BaseRowsetBuilder::_init_profile(profile);
104
0
    _commit_txn_timer = ADD_TIMER(_profile, "CommitTxnTime");
105
0
}
106
107
304k
BaseRowsetBuilder::~BaseRowsetBuilder() {
108
304k
    if (!_is_init) {
109
94.4k
        return;
110
94.4k
    }
111
112
209k
    if (_calc_delete_bitmap_token != nullptr) {
113
209k
        _calc_delete_bitmap_token->cancel();
114
209k
    }
115
209k
}
116
117
37.6k
RowsetBuilder::~RowsetBuilder() {
118
37.6k
    if (_is_init && !_is_committed) {
119
        // For txn rowset builders, we need to rollback txn when necessary.
120
7
        _garbage_collection(is_data_builder());
121
7
    }
122
37.6k
}
123
124
323k
Tablet* RowsetBuilder::tablet() {
125
323k
    return static_cast<Tablet*>(_tablet.get());
126
323k
}
127
128
7
void RowsetBuilder::_garbage_collection(bool cancel_txn) {
129
7
    Status rollback_status;
130
7
    bool need_clean = true;
131
7
    if (tablet() != nullptr && cancel_txn) {
132
6
        TxnManager* txn_mgr = _engine.txn_manager();
133
6
        rollback_status = txn_mgr->rollback_txn(_req.partition_id, *tablet(), _req.txn_id);
134
6
        need_clean = rollback_status.ok();
135
6
    }
136
    // has to check rollback status, because the rowset maybe committed in this thread and
137
    // published in another thread, then rollback will fail.
138
    // when rollback failed should not delete rowset
139
7
    if (need_clean) {
140
7
        _engine.add_unused_rowset(_rowset);
141
7
        for (auto& rs : _attach_rowsets) {
142
0
            _engine.add_unused_rowset(rs);
143
0
        }
144
7
    }
145
7
}
146
147
74.2k
Status BaseRowsetBuilder::init_mow_context(std::shared_ptr<MowContext>& mow_context) {
148
74.2k
    DCHECK(is_data_builder());
149
150
74.2k
    std::lock_guard<std::shared_mutex> lck(tablet()->get_header_lock());
151
74.2k
    _max_version_in_flush_phase = tablet()->max_version_unlocked();
152
74.2k
    std::vector<RowsetSharedPtr> rowset_ptrs;
153
    // tablet is under alter process. The delete bitmap will be calculated after conversion.
154
74.2k
    if (tablet()->tablet_state() == TABLET_NOTREADY) {
155
        // Disable 'partial_update' when the tablet is undergoing a 'schema changing process'
156
41
        if (_req.table_schema_param->is_partial_update()) {
157
0
            return Status::InternalError(
158
0
                    "Unable to do 'partial_update' when "
159
0
                    "the tablet is undergoing a 'schema changing process'");
160
0
        }
161
41
        _rowset_ids->clear();
162
74.2k
    } else {
163
74.2k
        RETURN_IF_ERROR(
164
74.2k
                tablet()->get_all_rs_id_unlocked(_max_version_in_flush_phase, _rowset_ids.get()));
165
74.2k
        rowset_ptrs = tablet()->get_rowset_by_ids(_rowset_ids.get());
166
74.2k
    }
167
74.2k
    _delete_bitmap = std::make_shared<DeleteBitmap>(tablet()->tablet_id());
168
74.2k
    mow_context = std::make_shared<MowContext>(_max_version_in_flush_phase, _req.txn_id,
169
74.2k
                                               _rowset_ids, rowset_ptrs, _delete_bitmap);
170
74.2k
    return Status::OK();
171
74.2k
}
172
173
36.5k
Status RowsetBuilder::check_tablet_version_count() {
174
36.5k
    DCHECK(is_data_builder());
175
176
36.5k
    auto max_version_config = _tablet->max_version_config();
177
36.5k
    auto version_count = tablet()->version_count();
178
36.5k
    DBUG_EXECUTE_IF("RowsetBuilder.check_tablet_version_count.too_many_version",
179
36.5k
                    { version_count = INT_MAX; });
180
    // Trigger TOO MANY VERSION error first
181
36.5k
    if (version_count > max_version_config) {
182
0
        return Status::Error<TOO_MANY_VERSION>(
183
0
                "failed to init rowset builder. version count: {}, exceed limit: {}, "
184
0
                "tablet: {}. Please reduce the frequency of loading data or adjust the "
185
0
                "max_tablet_version_num or time_series_max_tablet_version_num in be.conf to a "
186
0
                "larger value.",
187
0
                version_count, max_version_config, _tablet->tablet_id());
188
0
    }
189
    // (TODO Refrain) Maybe we can use a configurable param instead of hardcoded values '100'.
190
    // max_version_config must > 100, otherwise silent errors will occur.
191
36.5k
    if ((!config::disable_auto_compaction &&
192
36.5k
         !_tablet->tablet_meta()->tablet_schema()->disable_auto_compaction()) &&
193
36.5k
        (version_count > max_version_config - 100) &&
194
36.5k
        !GlobalMemoryArbitrator::is_exceed_soft_mem_limit(GB_EXCHANGE_BYTE)) {
195
        // Trigger compaction
196
0
        auto st = _engine.submit_compaction_task(std::static_pointer_cast<Tablet>(tablet_sptr()),
197
0
                                                 CompactionType::CUMULATIVE_COMPACTION, true, true,
198
0
                                                 2);
199
0
        if (!st.ok()) [[unlikely]] {
200
0
            LOG(WARNING) << "failed to trigger compaction, tablet_id=" << _tablet->tablet_id()
201
0
                         << " : " << st;
202
0
        }
203
0
    }
204
36.5k
    return Status::OK();
205
36.5k
}
206
207
36.5k
Status RowsetBuilder::prepare_txn() {
208
36.5k
    DCHECK(is_data_builder());
209
36.5k
    return tablet()->prepare_txn(_req.partition_id, _req.txn_id, _req.load_id, false);
210
36.5k
}
211
212
36.5k
Status RowsetBuilder::init() {
213
36.5k
    RowsetWriterContext context;
214
215
36.5k
    RETURN_IF_ERROR(_init_context_common_fields(context));
216
217
36.5k
    std::shared_ptr<MowContext> mow_context;
218
36.5k
    if (_tablet->enable_unique_key_merge_on_write()) {
219
22.5k
        RETURN_IF_ERROR(init_mow_context(mow_context));
220
22.5k
    }
221
222
36.5k
    RETURN_IF_ERROR(check_tablet_version_count());
223
224
36.5k
    auto version_count = tablet()->version_count() + tablet()->stale_version_count();
225
36.5k
    if (tablet()->avg_rs_meta_serialize_size() * version_count >
226
36.5k
        config::tablet_meta_serialize_size_limit) {
227
0
        return Status::Error<TOO_MANY_VERSION>(
228
0
                "failed to init rowset builder. meta serialize size : {}, exceed limit: {}, "
229
0
                "tablet: {}. Please reduce the frequency of loading data or adjust the "
230
0
                "max_tablet_version_num in be.conf to a larger value.",
231
0
                tablet()->avg_rs_meta_serialize_size() * version_count,
232
0
                config::tablet_meta_serialize_size_limit, _tablet->tablet_id());
233
0
    }
234
235
36.5k
    RETURN_IF_ERROR(prepare_txn());
236
237
36.5k
    DBUG_EXECUTE_IF("BaseRowsetBuilder::init.check_partial_update_column_num", {
238
36.5k
        if (_req.table_schema_param->partial_update_input_columns().size() !=
239
36.5k
            dp->param<int>("column_num")) {
240
36.5k
            return Status::InternalError("partial update input column num wrong!");
241
36.5k
        };
242
36.5k
    })
243
    // build tablet schema in request level
244
36.5k
    RETURN_IF_ERROR(_build_current_tablet_schema(_req.index_id, _req.table_schema_param.get(),
245
36.5k
                                                 *_tablet->tablet_schema()));
246
36.5k
    context.tablet_schema = _tablet_schema;
247
248
36.5k
    context.mow_context = mow_context;
249
250
36.5k
    context.partial_update_info = _partial_update_info;
251
36.5k
    _rowset_writer = DORIS_TRY(_tablet->create_rowset_writer(context, false));
252
36.5k
    _rowset_id = context.rowset_id;
253
36.5k
    std::vector<RowsetId> tmp_pending_rowset_ids = {_rowset_id};
254
36.5k
    tmp_pending_rowset_ids.resize(1 + _attach_rowset_ids.size());
255
36.5k
    std::copy(_attach_rowset_ids.begin(), _attach_rowset_ids.end(),
256
36.5k
              tmp_pending_rowset_ids.begin() + 1);
257
36.5k
    _pending_rs_guard = _engine.pending_local_rowsets().add(tmp_pending_rowset_ids);
258
259
36.5k
    _calc_delete_bitmap_token = _engine.calc_delete_bitmap_executor()->create_token();
260
261
36.5k
    _is_init = true;
262
36.5k
    return Status::OK();
263
36.5k
}
264
265
36.5k
Status BaseRowsetBuilder::_init_context_common_fields(RowsetWriterContext& context) {
266
36.5k
    _tablet = DORIS_TRY(ExecEnv::get_tablet(_req.tablet_id));
267
268
36.5k
    context.txn_id = _req.txn_id;
269
36.5k
    context.load_id = _req.load_id;
270
36.5k
    context.db_id = _req.table_schema_param->db_id();
271
36.5k
    context.table_id = _req.table_schema_param->table_id();
272
36.5k
    context.rowset_state = PREPARED;
273
36.5k
    context.segments_overlap = OVERLAPPING;
274
36.5k
    context.tablet_schema = _tablet_schema;
275
36.5k
    context.newest_write_timestamp = UnixSeconds();
276
36.5k
    context.tablet_id = _req.tablet_id;
277
36.5k
    context.index_id = _req.index_id;
278
36.5k
    context.tablet = _tablet;
279
36.5k
    context.enable_segcompaction = true;
280
36.5k
    if (_req.write_req_type == WriteRequestType::ROW_BINLOG || !_attach_rowset_ids.empty()) {
281
2
        context.enable_segcompaction = false;
282
2
    }
283
36.5k
    context.write_type = DataWriteType::TYPE_DIRECT;
284
36.5k
    context.write_file_cache = _req.write_file_cache;
285
286
36.5k
    return Status::OK();
287
36.5k
}
288
289
209k
Status BaseRowsetBuilder::build_rowset() {
290
209k
    std::lock_guard<std::mutex> l(_lock);
291
18.4E
    DCHECK(_is_init) << "rowset builder is supposed be to initialized before "
292
18.4E
                        "build_rowset() being called";
293
294
209k
    SCOPED_TIMER(_build_rowset_timer);
295
    // use rowset meta manager to save meta
296
209k
    RETURN_NOT_OK_STATUS_WITH_WARN(_rowset_writer->build(_rowset), "fail to build rowset");
297
209k
    return Status::OK();
298
209k
}
299
300
1
Status GroupRowsetBuilder::build_rowset() {
301
    // build binlog rowset first, then data rowset
302
    // If data rowset build fails after binlog has built some segments, we rely on the
303
    // RowsetBuilder/StorageEngine garbage-collection paths to clean up built-but-uncommitted files.
304
1
    RETURN_IF_ERROR(_row_binlog_rowset_builder->build_rowset());
305
1
    return _txn_rs_builder->build_rowset();
306
1
}
307
308
209k
Status BaseRowsetBuilder::submit_calc_delete_bitmap_task() {
309
209k
    DCHECK(is_data_builder());
310
209k
    if (!_tablet->enable_unique_key_merge_on_write() || _rowset->num_segments() == 0) {
311
177k
        return Status::OK();
312
177k
    }
313
32.1k
    std::lock_guard<std::mutex> l(_lock);
314
32.1k
    SCOPED_TIMER(_submit_delete_bitmap_timer);
315
32.2k
    if (_partial_update_info && _partial_update_info->is_flexible_partial_update()) {
316
264
        if (_rowset->num_segments() > 1) {
317
            // in flexible partial update, when there are more one segment in one load,
318
            // we need to do alignment process for same keys between segments, we haven't
319
            // implemented it yet and just report an error when encouter this situation
320
0
            return Status::NotSupported(
321
0
                    "too large input data in flexible partial update, Please "
322
0
                    "reduce the amount of data imported in a single load.");
323
0
        }
324
264
    }
325
326
32.1k
    auto* beta_rowset = reinterpret_cast<BetaRowset*>(_rowset.get());
327
32.1k
    std::vector<segment_v2::SegmentSharedPtr> segments;
328
32.1k
    RETURN_IF_ERROR(beta_rowset->load_segments(&segments));
329
32.1k
    if (segments.size() > 1) {
330
        // calculate delete bitmap between segments
331
0
        if (config::enable_calc_delete_bitmap_between_segments_concurrently) {
332
0
            RETURN_IF_ERROR(_calc_delete_bitmap_token->submit(
333
0
                    _tablet, _tablet_schema, _rowset->rowset_id(), segments, _delete_bitmap));
334
0
        } else {
335
0
            RETURN_IF_ERROR(_tablet->calc_delete_bitmap_between_segments(
336
0
                    _tablet_schema, _rowset->rowset_id(), segments, _delete_bitmap));
337
0
        }
338
0
    }
339
340
    // For partial update, we need to fill in the entire row of data, during the calculation
341
    // of the delete bitmap. This operation is resource-intensive, and we need to minimize
342
    // the number of times it occurs. Therefore, we skip this operation here.
343
32.1k
    if (_partial_update_info->is_partial_update()) {
344
        // for partial update, the delete bitmap calculation is done while append_block()
345
        // we print it's summarize logs here before commit.
346
1.68k
        LOG(INFO) << fmt::format(
347
1.68k
                "{} calc delete bitmap summary before commit: tablet({}), txn_id({}), "
348
1.68k
                "rowset_ids({}), cur max_version({}), bitmap num({}), bitmap_cardinality({}), num "
349
1.68k
                "rows updated({}), num rows new added({}), num rows deleted({}), total rows({})",
350
1.68k
                _partial_update_info->partial_update_mode_str(), tablet()->tablet_id(), _req.txn_id,
351
1.68k
                _rowset_ids->size(), rowset_writer()->context().mow_context->max_version,
352
1.68k
                _delete_bitmap->get_delete_bitmap_count(), _delete_bitmap->cardinality(),
353
1.68k
                rowset_writer()->num_rows_updated(), rowset_writer()->num_rows_new_added(),
354
1.68k
                rowset_writer()->num_rows_deleted(), rowset_writer()->num_rows());
355
1.68k
        return Status::OK();
356
1.68k
    }
357
358
32.1k
    LOG(INFO) << "submit calc delete bitmap task to executor, tablet_id: " << tablet()->tablet_id()
359
30.5k
              << ", txn_id: " << _req.txn_id;
360
30.5k
    return BaseTablet::commit_phase_update_delete_bitmap(_tablet, _rowset, *_rowset_ids,
361
30.5k
                                                         _delete_bitmap, segments, _req.txn_id,
362
30.5k
                                                         _calc_delete_bitmap_token.get(), nullptr);
363
32.1k
}
364
365
209k
Status BaseRowsetBuilder::wait_calc_delete_bitmap() {
366
209k
    DCHECK(is_data_builder());
367
209k
    if (!_tablet->enable_unique_key_merge_on_write() || _partial_update_info->is_partial_update()) {
368
138k
        return Status::OK();
369
138k
    }
370
70.7k
    std::lock_guard<std::mutex> l(_lock);
371
70.7k
    SCOPED_TIMER(_wait_delete_bitmap_timer);
372
70.7k
    RETURN_IF_ERROR(_calc_delete_bitmap_token->wait());
373
70.7k
    return Status::OK();
374
70.7k
}
375
376
36.5k
Status RowsetBuilder::commit_txn() {
377
36.5k
    DCHECK(is_data_builder());
378
36.5k
    if (tablet()->enable_unique_key_merge_on_write() &&
379
36.5k
        config::enable_merge_on_write_correctness_check && _rowset->num_rows() != 0 &&
380
36.5k
        tablet()->tablet_state() != TABLET_NOTREADY) {
381
11.2k
        auto st = tablet()->check_delete_bitmap_correctness(
382
11.2k
                _delete_bitmap, _rowset->end_version() - 1, _req.txn_id, *_rowset_ids);
383
11.2k
        if (!st.ok()) {
384
0
            LOG(WARNING) << fmt::format(
385
0
                    "[tablet_id:{}][txn_id:{}][load_id:{}][partition_id:{}] "
386
0
                    "delete bitmap correctness check failed in commit phase!",
387
0
                    _req.tablet_id, _req.txn_id, UniqueId(_req.load_id).to_string(),
388
0
                    _req.partition_id);
389
0
            return st;
390
0
        }
391
11.2k
    }
392
36.5k
    std::lock_guard<std::mutex> l(_lock);
393
36.5k
    SCOPED_TIMER(_commit_txn_timer);
394
395
    // Transfer ownership of `PendingRowsetGuard` to `TxnManager`
396
36.5k
    Status res = _engine.txn_manager()->commit_txn(
397
36.5k
            _req.partition_id, *tablet(), _req.txn_id, _req.load_id, _rowset,
398
36.5k
            std::move(_pending_rs_guard), false, _partial_update_info, &_attach_rowsets);
399
400
36.5k
    if (!res && !res.is<PUSH_TRANSACTION_ALREADY_EXIST>()) {
401
0
        LOG(WARNING) << "Failed to commit txn: " << _req.txn_id
402
0
                     << " for rowset: " << _rowset->rowset_id();
403
0
        return res;
404
0
    }
405
36.5k
    if (_tablet->enable_unique_key_merge_on_write()) {
406
        // no need to update binlog_delvec, it'll be updated in publish phase
407
22.5k
        _engine.txn_manager()->set_txn_related_delete_bitmap(
408
22.5k
                _req.partition_id, _req.txn_id, tablet()->tablet_id(), tablet()->tablet_uid(), true,
409
22.5k
                _delete_bitmap, *_rowset_ids, _partial_update_info);
410
22.5k
    }
411
412
36.5k
    _is_committed = true;
413
36.5k
    return Status::OK();
414
36.5k
}
415
416
0
Status BaseRowsetBuilder::cancel() {
417
0
    std::lock_guard<std::mutex> l(_lock);
418
0
    if (_is_cancelled) {
419
0
        return Status::OK();
420
0
    }
421
0
    if (_calc_delete_bitmap_token != nullptr) {
422
0
        _calc_delete_bitmap_token->cancel();
423
0
    }
424
0
    _is_cancelled = true;
425
0
    return Status::OK();
426
0
}
427
428
Status BaseRowsetBuilder::_build_current_tablet_schema(
429
        int64_t index_id, const OlapTableSchemaParam* table_schema_param,
430
208k
        const TabletSchema& ori_tablet_schema) {
431
208k
    const OlapTableIndexSchema* index_schema = nullptr;
432
208k
    if (_req.write_req_type == WriteRequestType::ROW_BINLOG) {
433
1
        const auto* row_binlog_index_schema = table_schema_param->row_binlog_index_schema();
434
1
        DCHECK(row_binlog_index_schema != nullptr);
435
1
        DCHECK_EQ(row_binlog_index_schema->index_id, index_id);
436
1
        index_schema = row_binlog_index_schema;
437
208k
    } else {
438
223k
        for (const auto* schema : table_schema_param->indexes()) {
439
223k
            if (schema->index_id == index_id) {
440
207k
                index_schema = schema;
441
207k
                break;
442
207k
            }
443
223k
        }
444
208k
    }
445
446
208k
    auto cache_key = TabletSchemaCache::build_load_schema_cache_key(
447
208k
            index_id, table_schema_param, ori_tablet_schema, index_schema);
448
208k
    auto cached_schema = TabletSchemaCache::instance()->lookup_schema(cache_key);
449
208k
    if (cached_schema.first != nullptr) {
450
152k
        _tablet_schema = cached_schema.second;
451
152k
        TabletSchemaCache::instance()->release(cached_schema.first);
452
152k
    } else {
453
57.1k
        if (index_schema != nullptr && !index_schema->columns.empty() &&
454
57.1k
            index_schema->columns[0]->unique_id() >= 0) {
455
57.1k
            _tablet_schema->shawdow_copy_without_columns(ori_tablet_schema);
456
57.1k
            _tablet_schema->build_current_tablet_schema(
457
57.1k
                    index_id, cast_set<int32_t>(table_schema_param->version()), index_schema,
458
57.1k
                    ori_tablet_schema);
459
18.4E
        } else {
460
18.4E
            _tablet_schema->copy_from(ori_tablet_schema);
461
18.4E
        }
462
55.7k
        _tablet_schema->set_table_id(table_schema_param->table_id());
463
55.7k
        _tablet_schema->set_db_id(table_schema_param->db_id());
464
55.7k
        if (table_schema_param->is_partial_update()) {
465
828
            _tablet_schema->set_auto_increment_column(table_schema_param->auto_increment_coulumn());
466
828
        }
467
55.7k
        auto inserted_schema = TabletSchemaCache::instance()->insert(cache_key, _tablet_schema);
468
55.7k
        _tablet_schema = inserted_schema.second;
469
55.7k
        TabletSchemaCache::instance()->release(inserted_schema.first);
470
55.7k
    }
471
208k
    if (_tablet_schema->schema_version() > ori_tablet_schema.schema_version()) {
472
        // After schema change, should include extracted column
473
        // For example: a table has two columns, k and v
474
        // After adding a column v2, the schema version increases, max_version_schema needs to be updated.
475
        // _tablet_schema includes k, v, and v2
476
        // if v is a variant, need to add the columns decomposed from the v to the _tablet_schema.
477
1.35k
        if (is_data_builder()) {
478
1.35k
            if (_tablet_schema->num_variant_columns() > 0) {
479
99
                TabletSchemaSPtr max_version_schema = std::make_shared<TabletSchema>();
480
99
                max_version_schema->copy_from(*_tablet_schema);
481
99
                max_version_schema->copy_extracted_columns(ori_tablet_schema);
482
99
                _tablet->update_max_version_schema(max_version_schema);
483
1.25k
            } else {
484
1.25k
                _tablet->update_max_version_schema(_tablet_schema);
485
1.25k
            }
486
1.35k
        }
487
1.35k
    }
488
489
    // set partial update columns info
490
209k
    if (is_data_builder()) {
491
209k
        _partial_update_info = std::make_shared<PartialUpdateInfo>();
492
209k
        RETURN_IF_ERROR(_partial_update_info->init(
493
209k
                tablet()->tablet_id(), _req.txn_id, *_tablet_schema,
494
209k
                table_schema_param->unique_key_update_mode(),
495
209k
                table_schema_param->partial_update_new_key_policy(),
496
209k
                table_schema_param->partial_update_input_columns(),
497
209k
                table_schema_param->is_strict_mode(), table_schema_param->timestamp_ms(),
498
209k
                table_schema_param->nano_seconds(), table_schema_param->timezone(),
499
209k
                table_schema_param->auto_increment_coulumn(),
500
209k
                table_schema_param->sequence_map_col_uid(), _max_version_in_flush_phase));
501
209k
    }
502
208k
    return Status::OK();
503
208k
}
504
505
GroupRowsetBuilder::GroupRowsetBuilder(StorageEngine& engine, const WriteRequest& group_build_req,
506
                                       const WriteRequest& sub_data_req,
507
                                       const WriteRequest& sub_row_binlog_req,
508
                                       RuntimeProfile* profile)
509
1
        : BaseRowsetBuilder(group_build_req, profile) {
510
1
    DCHECK(group_build_req.write_req_type == WriteRequestType::GROUP &&
511
1
           sub_data_req.write_req_type == WriteRequestType::DATA &&
512
1
           sub_row_binlog_req.write_req_type == WriteRequestType::ROW_BINLOG);
513
1
    _row_binlog_rowset_builder =
514
1
            std::make_shared<RowBinlogRowsetBuilder>(engine, sub_row_binlog_req, profile);
515
1
    _txn_rs_builder = std::make_shared<RowsetBuilder>(engine, sub_data_req, profile);
516
1
}
517
518
1
Status GroupRowsetBuilder::init() {
519
    // init binlog builder first so that its rowset id can be added into
520
    // PendingLocalRowsets before txn builder init.
521
1
    RETURN_IF_ERROR(_row_binlog_rowset_builder->init());
522
    // before init txn, need to add all rowset_ids into PendingLocalRowsets.
523
    // see https://github.com/apache/doris/pull/25921
524
1
    RETURN_IF_ERROR(_txn_rs_builder->attach_pending_rs_guard_to_txn(
525
1
            _row_binlog_rowset_builder->rowset_id()));
526
1
    RETURN_IF_ERROR(_txn_rs_builder->init());
527
528
    // Create a GroupRowsetWriter that forwards flush to both underlying
529
    // RowsetWriters.
530
1
    std::unique_ptr<doris::GroupRowsetWriter> group_writer;
531
1
    RETURN_IF_ERROR(RowsetFactory::create_empty_group_rowset_writer(&group_writer));
532
1
    group_writer->set_data_writer(_txn_rs_builder->rowset_writer());
533
1
    group_writer->set_row_binlog_writer(_row_binlog_rowset_builder->rowset_writer());
534
535
1
    {
536
1
        const auto& data_ctx = _txn_rs_builder->rowset_writer()->context();
537
1
        auto& binlog_ctx = const_cast<RowsetWriterContext&>(
538
1
                _row_binlog_rowset_builder->rowset_writer()->context());
539
1
        auto& cfg = binlog_ctx.write_binlog_opt().write_binlog_config();
540
1
        cfg.source.tablet_schema = data_ctx.tablet_schema;
541
1
        cfg.source.partial_update_info = data_ctx.partial_update_info;
542
1
        cfg.source.mow_context = data_ctx.mow_context;
543
1
        cfg.source.is_transient_rowset_writer = data_ctx.is_transient_rowset_writer;
544
1
        cfg.source.source_write_type = data_ctx.write_type;
545
1
    }
546
547
1
    _rowset_writer = std::move(group_writer);
548
1
    _is_init = true;
549
1
    return Status::OK();
550
1
}
551
552
0
Status GroupRowsetBuilder::submit_calc_delete_bitmap_task() {
553
0
    return _txn_rs_builder->submit_calc_delete_bitmap_task();
554
0
}
555
556
0
Status GroupRowsetBuilder::wait_calc_delete_bitmap() {
557
0
    return _txn_rs_builder->wait_calc_delete_bitmap();
558
0
}
559
560
0
Status GroupRowsetBuilder::commit_txn() {
561
    // Attach binlog rowset to txn rowset, so that commit/rollback and
562
    // clean-up are all handled by txn rowset builder.
563
0
    RETURN_IF_ERROR(_txn_rs_builder->attach_rowset_to_txn(_row_binlog_rowset_builder->rowset()));
564
0
    auto st = _txn_rs_builder->commit_txn();
565
0
    if (st.ok()) {
566
        // Avoid RowBinlogRowsetBuilder being cleaned in its base dtor.
567
0
        RETURN_IF_ERROR(_row_binlog_rowset_builder->commit_txn());
568
0
    }
569
0
    return st;
570
0
}
571
572
1
Status RowBinlogRowsetBuilder::init() {
573
1
    RowsetWriterContext context;
574
575
1
    RETURN_IF_ERROR(_init_context_common_fields(context));
576
577
    // build tablet schema in request level
578
1
    RETURN_IF_ERROR(_build_current_tablet_schema(
579
1
            _req.index_id, _req.table_schema_param.get(),
580
1
            *std::dynamic_pointer_cast<Tablet>(_tablet)->row_binlog_tablet_schema()));
581
1
    context.tablet_schema = _tablet_schema;
582
1
    context.write_binlog_opt().enable = true;
583
584
1
    _rowset_writer = DORIS_TRY(_tablet->create_rowset_writer(context, false));
585
    // need to attach PendingRowsetGuard after txn_rs_builder init
586
1
    _rowset_id = context.rowset_id;
587
588
1
    _is_init = true;
589
1
    return Status::OK();
590
1
}
591
592
0
Status BaseRowsetBuilder::attach_rowset_to_txn(const RowsetSharedPtr& rowset) {
593
0
    if (!is_data_builder()) {
594
0
        return Status::RuntimeError("the rowset isn't allowed to manage txn");
595
0
    }
596
0
    _attach_rowsets.push_back(rowset);
597
0
    return Status::OK();
598
0
}
599
600
1
Status BaseRowsetBuilder::attach_pending_rs_guard_to_txn(const RowsetId& rowset_id) {
601
1
    if (!is_data_builder()) {
602
0
        return Status::RuntimeError("the rowset isn't allowed to manage txn");
603
0
    }
604
1
    _attach_rowset_ids.push_back(rowset_id);
605
1
    return Status::OK();
606
1
}
607
608
} // namespace doris