Coverage Report

Created: 2026-08-10 05:17

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/storage/tablet/base_tablet.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/tablet/base_tablet.h"
19
20
#include <bthread/mutex.h>
21
#include <crc32c/crc32c.h>
22
#include <fmt/format.h>
23
#include <rapidjson/prettywriter.h>
24
25
#include <algorithm>
26
#include <cstdint>
27
#include <iterator>
28
#include <random>
29
#include <shared_mutex>
30
31
#include "cloud/cloud_tablet.h"
32
#include "cloud/config.h"
33
#include "common/cast_set.h"
34
#include "common/logging.h"
35
#include "common/metrics/doris_metrics.h"
36
#include "common/status.h"
37
#include "core/assert_cast.h"
38
#include "core/column/column_vector.h"
39
#include "core/data_type/data_type_factory.hpp"
40
#include "cpp/sync_point.h"
41
#include "load/memtable/memtable.h"
42
#include "service/point_query_executor.h"
43
#include "storage/binlog.h"
44
#include "storage/compaction/cumulative_compaction_time_series_policy.h"
45
#include "storage/delete/calc_delete_bitmap_executor.h"
46
#include "storage/delete/delete_bitmap_calculator.h"
47
#include "storage/index/primary_key_index.h"
48
#include "storage/iterators.h"
49
#include "storage/partial_update_info.h"
50
#include "storage/rowid_conversion.h"
51
#include "storage/rowset/beta_rowset.h"
52
#include "storage/rowset/group_rowset_writer.h"
53
#include "storage/rowset/rowset.h"
54
#include "storage/rowset/rowset_factory.h"
55
#include "storage/rowset/rowset_fwd.h"
56
#include "storage/rowset/rowset_reader.h"
57
#include "storage/rowset/rowset_writer_context.h"
58
#include "storage/segment/column_reader.h"
59
#include "storage/tablet/tablet_fwd.h"
60
#include "storage/txn/txn_manager.h"
61
#include "util/bvar_helper.h"
62
#include "util/debug_points.h"
63
#include "util/jsonb/serialize.h"
64
65
namespace doris {
66
67
using namespace ErrorCode;
68
69
namespace {
70
71
bvar::LatencyRecorder g_tablet_commit_phase_update_delete_bitmap_latency(
72
        "doris_pk", "commit_phase_update_delete_bitmap");
73
bvar::LatencyRecorder g_tablet_lookup_rowkey_latency("doris_pk", "tablet_lookup_rowkey");
74
bvar::Adder<uint64_t> g_tablet_pk_not_found("doris_pk", "lookup_not_found");
75
bvar::PerSecond<bvar::Adder<uint64_t>> g_tablet_pk_not_found_per_second(
76
        "doris_pk", "lookup_not_found_per_second", &g_tablet_pk_not_found, 60);
77
bvar::LatencyRecorder g_tablet_update_delete_bitmap_latency("doris_pk", "update_delete_bitmap");
78
79
static bvar::Adder<size_t> g_total_tablet_num("doris_total_tablet_num");
80
81
Status _get_segment_column_iterator(const BetaRowsetSharedPtr& rowset, uint32_t segid,
82
                                    const TabletColumn& target_column,
83
                                    SegmentCacheHandle* segment_cache_handle,
84
                                    std::unique_ptr<segment_v2::ColumnIterator>* column_iterator,
85
                                    OlapReaderStatistics* stats,
86
8.80k
                                    const io::IOContext* input_io_ctx = nullptr) {
87
8.80k
    RETURN_IF_ERROR(SegmentLoader::instance()->load_segments(rowset, segment_cache_handle, true,
88
8.80k
                                                             false, stats, input_io_ctx));
89
    // find segment
90
8.80k
    auto it = std::find_if(
91
8.80k
            segment_cache_handle->get_segments().begin(),
92
8.80k
            segment_cache_handle->get_segments().end(),
93
8.82k
            [&segid](const segment_v2::SegmentSharedPtr& seg) { return seg->id() == segid; });
94
8.80k
    if (it == segment_cache_handle->get_segments().end()) {
95
0
        return Status::NotFound(fmt::format("rowset {} 's segemnt not found, seg_id {}",
96
0
                                            rowset->rowset_id().to_string(), segid));
97
0
    }
98
8.80k
    segment_v2::SegmentSharedPtr segment = *it;
99
8.80k
    StorageReadOptions opts;
100
8.80k
    opts.stats = stats;
101
8.80k
    if (input_io_ctx != nullptr) {
102
4.67k
        opts.io_ctx = *input_io_ctx;
103
4.67k
    }
104
8.80k
    RETURN_IF_ERROR(segment->new_column_iterator(target_column, column_iterator, &opts));
105
8.80k
    auto io_ctx = opts.io_ctx;
106
8.80k
    io_ctx.reader_type = ReaderType::READER_QUERY;
107
8.80k
    io_ctx.file_cache_stats = &stats->file_cache_stats;
108
8.80k
    segment_v2::ColumnIteratorOptions opt {
109
8.80k
            .use_page_cache = !config::disable_storage_page_cache,
110
8.80k
            .file_reader = segment->file_reader().get(),
111
8.80k
            .stats = stats,
112
8.80k
            .io_ctx = io_ctx,
113
8.80k
    };
114
8.80k
    RETURN_IF_ERROR((*column_iterator)->init(opt));
115
8.80k
    return Status::OK();
116
8.80k
}
117
118
} // namespace
119
120
extern MetricPrototype METRIC_query_scan_bytes;
121
extern MetricPrototype METRIC_query_scan_rows;
122
extern MetricPrototype METRIC_query_scan_count;
123
DEFINE_COUNTER_METRIC_PROTOTYPE_2ARG(flush_bytes, MetricUnit::BYTES);
124
DEFINE_COUNTER_METRIC_PROTOTYPE_2ARG(flush_finish_count, MetricUnit::OPERATIONS);
125
126
414k
BaseTablet::BaseTablet(TabletMetaSharedPtr tablet_meta) : _tablet_meta(std::move(tablet_meta)) {
127
414k
    _metric_entity = DorisMetrics::instance()->metric_registry()->register_entity(
128
414k
            fmt::format("Tablet.{}", tablet_id()), {{"tablet_id", std::to_string(tablet_id())}},
129
414k
            MetricEntityType::kTablet);
130
414k
    INT_COUNTER_METRIC_REGISTER(_metric_entity, query_scan_bytes);
131
414k
    INT_COUNTER_METRIC_REGISTER(_metric_entity, query_scan_rows);
132
414k
    INT_COUNTER_METRIC_REGISTER(_metric_entity, query_scan_count);
133
414k
    INT_COUNTER_METRIC_REGISTER(_metric_entity, flush_bytes);
134
414k
    INT_COUNTER_METRIC_REGISTER(_metric_entity, flush_finish_count);
135
136
    // construct _timestamped_versioned_tracker from rs and stale rs meta
137
414k
    _timestamped_version_tracker.construct_versioned_tracker(_tablet_meta->all_rs_metas(),
138
414k
                                                             _tablet_meta->all_stale_rs_metas());
139
140
    // if !_tablet_meta->all_rs_metas()[0]->tablet_schema(),
141
    // that mean the tablet_meta is still no upgrade to doris 1.2 versions.
142
    // Before doris 1.2 version, rowset metas don't have tablet schema.
143
    // And when upgrade to doris 1.2 version,
144
    // all rowset metas will be set the tablet schmea from tablet meta.
145
414k
    if (_tablet_meta->all_rs_metas().empty() ||
146
414k
        !_tablet_meta->all_rs_metas().begin()->second->tablet_schema()) {
147
129k
        _max_version_schema = _tablet_meta->tablet_schema();
148
284k
    } else {
149
284k
        std::vector<RowsetMetaSharedPtr> rowset_metas(_tablet_meta->all_rs_metas().size());
150
284k
        std::transform(_tablet_meta->all_rs_metas().begin(), _tablet_meta->all_rs_metas().end(),
151
482k
                       rowset_metas.begin(), [](const auto& it) { return it.second; });
152
284k
        _max_version_schema = tablet_schema_with_merged_max_schema_version(rowset_metas);
153
284k
    }
154
414k
    DCHECK(_max_version_schema);
155
414k
    g_total_tablet_num << 1;
156
414k
}
157
158
172k
BaseTablet::~BaseTablet() {
159
172k
    DorisMetrics::instance()->metric_registry()->deregister_entity(_metric_entity);
160
172k
    g_total_tablet_num << -1;
161
172k
}
162
163
TabletSchemaSPtr BaseTablet::tablet_schema_with_merged_max_schema_version(
164
295k
        const std::vector<RowsetMetaSharedPtr>& rowset_metas) {
165
295k
    RowsetMetaSharedPtr max_schema_version_rs = *std::max_element(
166
295k
            rowset_metas.begin(), rowset_metas.end(), [](const auto& a, const auto& b) -> bool {
167
282k
                return !a->tablet_schema()
168
282k
                               ? true
169
282k
                               : (!b->tablet_schema()
170
282k
                                          ? false
171
282k
                                          : a->tablet_schema()->schema_version() <
172
282k
                                                    b->tablet_schema()->schema_version());
173
282k
            });
174
295k
    return max_schema_version_rs->tablet_schema();
175
295k
}
176
177
16.8k
Status BaseTablet::set_tablet_state(TabletState state) {
178
16.8k
    if (_tablet_meta->tablet_state() == TABLET_SHUTDOWN && state != TABLET_SHUTDOWN) {
179
0
        return Status::Error<META_INVALID_ARGUMENT>(
180
0
                "could not change tablet state from shutdown to {}", state);
181
0
    }
182
16.8k
    _tablet_meta->set_tablet_state(state);
183
16.8k
    return Status::OK();
184
16.8k
}
185
186
2.74k
void BaseTablet::update_max_version_schema(const TabletSchemaSPtr& tablet_schema) {
187
2.74k
    std::lock_guard wrlock(_meta_lock);
188
    // Double Check for concurrent update
189
2.74k
    if (!_max_version_schema ||
190
2.74k
        tablet_schema->schema_version() > _max_version_schema->schema_version()) {
191
2.28k
        _max_version_schema = tablet_schema;
192
2.28k
    }
193
2.74k
}
194
195
210k
uint32_t BaseTablet::get_real_compaction_score() const {
196
210k
    std::shared_lock l(_meta_lock);
197
210k
    return get_real_compaction_score_unlocked();
198
210k
}
199
200
500k
uint32_t BaseTablet::get_real_compaction_score_unlocked() const {
201
500k
    const auto& rs_metas = _tablet_meta->all_rs_metas();
202
1.04M
    return std::accumulate(rs_metas.begin(), rs_metas.end(), 0, [](uint32_t score, const auto& it) {
203
1.04M
        return score + it.second->get_compaction_score();
204
1.04M
    });
205
500k
}
206
207
Status BaseTablet::capture_rs_readers_unlocked(const Versions& version_path,
208
20
                                               std::vector<RowSetSplits>* rs_splits) const {
209
20
    DCHECK(rs_splits != nullptr && rs_splits->empty());
210
40
    for (auto version : version_path) {
211
40
        auto it = _rs_version_map.find(version);
212
40
        if (it == _rs_version_map.end()) {
213
0
            VLOG_NOTICE << "fail to find Rowset in rs_version for version. tablet=" << tablet_id()
214
0
                        << ", version='" << version.first << "-" << version.second;
215
216
0
            it = _stale_rs_version_map.find(version);
217
0
            if (it == _stale_rs_version_map.end()) {
218
0
                return Status::Error<CAPTURE_ROWSET_READER_ERROR>(
219
0
                        "fail to find Rowset in stale_rs_version for version. tablet={}, "
220
0
                        "version={}-{}",
221
0
                        tablet_id(), version.first, version.second);
222
0
            }
223
0
        }
224
40
        RowsetReaderSharedPtr rs_reader;
225
40
        auto res = it->second->create_reader(&rs_reader);
226
40
        if (!res.ok()) {
227
0
            return Status::Error<CAPTURE_ROWSET_READER_ERROR>(
228
0
                    "failed to create reader for rowset:{}", it->second->rowset_id().to_string());
229
0
        }
230
40
        rs_splits->emplace_back(std::move(rs_reader));
231
40
    }
232
20
    return Status::OK();
233
20
}
234
235
// snapshot manager may call this api to check if version exists, so that
236
// the version maybe not exist
237
RowsetSharedPtr BaseTablet::get_rowset_by_version(const Version& version,
238
255k
                                                  bool find_in_stale) const {
239
255k
    auto iter = _rs_version_map.find(version);
240
255k
    if (iter == _rs_version_map.end()) {
241
128k
        if (find_in_stale) {
242
0
            return get_stale_rowset_by_version(version);
243
0
        }
244
128k
        return nullptr;
245
128k
    }
246
127k
    return iter->second;
247
255k
}
248
249
0
RowsetSharedPtr BaseTablet::get_stale_rowset_by_version(const Version& version) const {
250
0
    auto iter = _stale_rs_version_map.find(version);
251
0
    if (iter == _stale_rs_version_map.end()) {
252
0
        VLOG_NOTICE << "no rowset for version:" << version << ", tablet: " << tablet_id();
253
0
        return nullptr;
254
0
    }
255
0
    return iter->second;
256
0
}
257
258
// Already under _meta_lock
259
189k
RowsetSharedPtr BaseTablet::get_rowset_with_max_version() const {
260
189k
    Version max_version = _tablet_meta->max_version();
261
189k
    if (max_version.first == -1) {
262
0
        return nullptr;
263
0
    }
264
265
189k
    auto iter = _rs_version_map.find(max_version);
266
189k
    if (iter == _rs_version_map.end()) {
267
0
        DCHECK(false) << "invalid version:" << max_version;
268
0
        return nullptr;
269
0
    }
270
189k
    return iter->second;
271
189k
}
272
273
14
Status BaseTablet::get_all_rs_id(int64_t max_version, RowsetIdUnorderedSet* rowset_ids) const {
274
14
    std::shared_lock rlock(_meta_lock);
275
14
    return get_all_rs_id_unlocked(max_version, rowset_ids);
276
14
}
277
278
Status BaseTablet::get_all_rs_id_unlocked(int64_t max_version,
279
176k
                                          RowsetIdUnorderedSet* rowset_ids) const {
280
    //  Ensure that the obtained versions of rowsets are continuous
281
176k
    Version spec_version(0, max_version);
282
176k
    Versions version_path;
283
176k
    auto st = _timestamped_version_tracker.capture_consistent_versions(spec_version, &version_path);
284
176k
    if (!st.ok()) [[unlikely]] {
285
0
        return st;
286
0
    }
287
288
1.41M
    for (auto& ver : version_path) {
289
1.41M
        if (ver.second == 1) {
290
            // [0-1] rowset is empty for each tablet, skip it
291
176k
            continue;
292
176k
        }
293
1.24M
        auto it = _rs_version_map.find(ver);
294
1.24M
        if (it == _rs_version_map.end()) {
295
0
            return Status::Error<CAPTURE_ROWSET_ERROR, false>(
296
0
                    "fail to find Rowset for version. tablet={}, version={}", tablet_id(),
297
0
                    ver.to_string());
298
0
        }
299
1.24M
        rowset_ids->emplace(it->second->rowset_id());
300
1.24M
    }
301
176k
    return Status::OK();
302
176k
}
303
304
0
Versions BaseTablet::get_missed_versions(int64_t spec_version) const {
305
0
    DCHECK(spec_version > 0) << "invalid spec_version: " << spec_version;
306
307
0
    Versions existing_versions;
308
0
    {
309
0
        std::shared_lock rdlock(_meta_lock);
310
0
        for (const auto& [ver, _] : _tablet_meta->all_rs_metas()) {
311
0
            existing_versions.emplace_back(ver);
312
0
        }
313
0
    }
314
0
    return calc_missed_versions(spec_version, std::move(existing_versions));
315
0
}
316
317
1.26k
Versions BaseTablet::get_missed_versions_unlocked(int64_t spec_version) const {
318
1.26k
    DCHECK(spec_version > 0) << "invalid spec_version: " << spec_version;
319
320
1.26k
    Versions existing_versions;
321
4.01k
    for (const auto& [ver, _] : _tablet_meta->all_rs_metas()) {
322
4.01k
        existing_versions.emplace_back(ver);
323
4.01k
    }
324
1.26k
    return calc_missed_versions(spec_version, std::move(existing_versions));
325
1.26k
}
326
327
2
void BaseTablet::_print_missed_versions(const Versions& missed_versions) const {
328
2
    std::stringstream ss;
329
2
    ss << tablet_id() << " has " << missed_versions.size() << " missed version:";
330
    // print at most 10 version
331
6
    for (int i = 0; i < 10 && i < missed_versions.size(); ++i) {
332
4
        ss << missed_versions[i] << ",";
333
4
    }
334
2
    LOG(WARNING) << ss.str();
335
2
}
336
337
3.68k
bool BaseTablet::_reconstruct_version_tracker_if_necessary() {
338
3.68k
    double data_orphan_vertex_ratio = _timestamped_version_tracker.get_orphan_vertex_ratio();
339
3.68k
    if (data_orphan_vertex_ratio >= config::tablet_version_graph_orphan_vertex_ratio) {
340
3.62k
        _timestamped_version_tracker.construct_versioned_tracker(
341
3.62k
                _tablet_meta->all_rs_metas(), _tablet_meta->all_stale_rs_metas());
342
3.62k
        return true;
343
3.62k
    }
344
66
    return false;
345
3.68k
}
346
347
// should use this method to get a copy of current tablet meta
348
// there are some rowset meta in local meta store and in in-memory tablet meta
349
// but not in tablet meta in local meta store
350
void BaseTablet::generate_tablet_meta_copy(TabletMeta& new_tablet_meta,
351
2
                                           bool cloud_get_rowset_meta) const {
352
2
    std::shared_lock rdlock(_meta_lock);
353
2
    generate_tablet_meta_copy_unlocked(new_tablet_meta, cloud_get_rowset_meta);
354
2
}
355
356
// this is a unlocked version of generate_tablet_meta_copy()
357
// some method already hold the _meta_lock before calling this,
358
// such as EngineCloneTask::_finish_clone -> tablet->revise_tablet_meta
359
void BaseTablet::generate_tablet_meta_copy_unlocked(TabletMeta& new_tablet_meta,
360
322
                                                    bool cloud_get_rowset_meta) const {
361
322
    TabletMetaPB tablet_meta_pb;
362
322
    _tablet_meta->to_meta_pb(&tablet_meta_pb, cloud_get_rowset_meta);
363
322
    new_tablet_meta.init_from_pb(tablet_meta_pb);
364
322
}
365
366
Status BaseTablet::calc_delete_bitmap_between_segments(
367
        TabletSchemaSPtr schema, RowsetId rowset_id,
368
        const std::vector<segment_v2::SegmentSharedPtr>& segments, DeleteBitmapPtr delete_bitmap,
369
19
        int64_t queue_time_us) {
370
19
    size_t const num_segments = segments.size();
371
19
    if (num_segments < 2) {
372
19
        return Status::OK();
373
19
    }
374
375
0
    OlapStopWatch watch;
376
0
    size_t seq_col_length = 0;
377
0
    if (schema->has_sequence_col()) {
378
0
        auto seq_col_idx = schema->sequence_col_idx();
379
0
        seq_col_length = schema->column(seq_col_idx).length() + 1;
380
0
    }
381
0
    size_t rowid_length = 0;
382
0
    if (!schema->cluster_key_uids().empty()) {
383
0
        rowid_length = PrimaryKeyIndexReader::ROW_ID_LENGTH;
384
0
    }
385
386
0
    MergeIndexDeleteBitmapCalculator calculator;
387
0
    RETURN_IF_ERROR(calculator.init(rowset_id, segments, seq_col_length, rowid_length));
388
389
0
    RETURN_IF_ERROR(calculator.calculate_all(delete_bitmap));
390
391
0
    delete_bitmap->add(
392
0
            {rowset_id, DeleteBitmap::INVALID_SEGMENT_ID, DeleteBitmap::TEMP_VERSION_COMMON},
393
0
            DeleteBitmap::ROWSET_SENTINEL_MARK);
394
0
    LOG(INFO) << fmt::format(
395
0
            "construct delete bitmap between segments, "
396
0
            "tablet: {}, rowset: {}, number of segments: {}, bitmap count: {}, bitmap cardinality: "
397
0
            "{}, queue_time_us: {}, cost {} (us)",
398
0
            tablet_id(), rowset_id.to_string(), num_segments,
399
0
            delete_bitmap->get_delete_bitmap_count(), delete_bitmap->cardinality(), queue_time_us,
400
0
            watch.get_elapse_time_us());
401
0
    return Status::OK();
402
0
}
403
404
std::vector<RowsetSharedPtr> BaseTablet::get_rowset_by_ids(
405
212k
        const RowsetIdUnorderedSet* specified_rowset_ids) {
406
212k
    std::vector<RowsetSharedPtr> rowsets;
407
1.73M
    for (auto& rs : _rs_version_map) {
408
1.73M
        if (!specified_rowset_ids ||
409
1.73M
            specified_rowset_ids->find(rs.second->rowset_id()) != specified_rowset_ids->end()) {
410
874k
            rowsets.push_back(rs.second);
411
874k
        }
412
1.73M
    }
413
414
2.89M
    std::sort(rowsets.begin(), rowsets.end(), [](RowsetSharedPtr& lhs, RowsetSharedPtr& rhs) {
415
2.89M
        return lhs->end_version() > rhs->end_version();
416
2.89M
    });
417
212k
    return rowsets;
418
212k
}
419
420
Status BaseTablet::lookup_row_data(const Slice& encoded_key, const RowLocation& row_location,
421
                                   RowsetSharedPtr input_rowset, OlapReaderStatistics& stats,
422
                                   std::string& values, bool write_to_cache,
423
4.67k
                                   const io::IOContext* io_ctx) {
424
4.67k
    MonotonicStopWatch watch;
425
4.67k
    size_t row_size = 1;
426
4.67k
    watch.start();
427
4.67k
    Defer _defer([&]() {
428
4.67k
        LOG_EVERY_N(INFO, 500) << "get a single_row, cost(us):" << watch.elapsed_time() / 1000
429
10
                               << ", row_size:" << row_size;
430
4.67k
    });
431
432
4.67k
    BetaRowsetSharedPtr rowset = std::static_pointer_cast<BetaRowset>(input_rowset);
433
4.67k
    CHECK(rowset);
434
4.67k
    const TabletSchemaSPtr tablet_schema = rowset->tablet_schema();
435
4.67k
    SegmentCacheHandle segment_cache_handle;
436
4.67k
    std::unique_ptr<segment_v2::ColumnIterator> column_iterator;
437
4.67k
    const auto& column = *DORIS_TRY(tablet_schema->column(BeConsts::ROW_STORE_COL));
438
4.67k
    RETURN_IF_ERROR(_get_segment_column_iterator(rowset, row_location.segment_id, column,
439
4.67k
                                                 &segment_cache_handle, &column_iterator, &stats,
440
4.67k
                                                 io_ctx));
441
    // get and parse tuple row
442
4.67k
    MutableColumnPtr column_ptr = ColumnString::create();
443
4.67k
    std::vector<segment_v2::rowid_t> rowids {static_cast<segment_v2::rowid_t>(row_location.row_id)};
444
4.67k
    RETURN_IF_ERROR(column_iterator->read_by_rowids(rowids.data(), 1, column_ptr));
445
4.67k
    assert(column_ptr->size() == 1);
446
4.67k
    auto* string_column = static_cast<ColumnString*>(column_ptr.get());
447
4.67k
    StringRef value = string_column->get_data_at(0);
448
4.67k
    values = value.to_string();
449
4.67k
    if (write_to_cache) {
450
0
        RowCache::instance()->insert({tablet_id(), encoded_key}, Slice {value.data, value.size});
451
0
    }
452
4.67k
    return Status::OK();
453
4.67k
}
454
455
// NOLINTNEXTLINE(readability-function-size): Keep the existing rowset lookup flow together.
456
Status BaseTablet::lookup_row_key(const Slice& encoded_key, TabletSchema* latest_schema,
457
                                  bool with_seq_col,
458
                                  const std::vector<RowsetSharedPtr>& specified_rowsets,
459
                                  RowLocation* row_location, int64_t version,
460
                                  std::vector<std::unique_ptr<SegmentCacheHandle>>& segment_caches,
461
                                  RowsetSharedPtr* rowset, bool with_rowid,
462
                                  std::string* encoded_seq_value, OlapReaderStatistics* stats,
463
3.68M
                                  DeleteBitmapPtr delete_bitmap, const io::IOContext* io_ctx) {
464
3.68M
    SCOPED_BVAR_LATENCY(g_tablet_lookup_rowkey_latency);
465
3.68M
    size_t seq_col_length = 0;
466
    // use the latest tablet schema to decide if the tablet has sequence column currently
467
3.68M
    const TabletSchema* schema =
468
3.68M
            (latest_schema == nullptr ? _tablet_meta->tablet_schema().get() : latest_schema);
469
3.68M
    if (schema->has_sequence_col() && with_seq_col) {
470
23.3k
        seq_col_length = schema->column(schema->sequence_col_idx()).length() + 1;
471
23.3k
    }
472
3.68M
    size_t rowid_length = 0;
473
3.68M
    if (with_rowid && !schema->cluster_key_uids().empty()) {
474
66.2k
        rowid_length = PrimaryKeyIndexReader::ROW_ID_LENGTH;
475
66.2k
    }
476
3.68M
    Slice key_without_seq =
477
3.68M
            Slice(encoded_key.get_data(), encoded_key.get_size() - seq_col_length - rowid_length);
478
3.68M
    RowLocation loc;
479
480
3.68M
    auto tablet_delete_bitmap =
481
3.68M
            delete_bitmap == nullptr ? _tablet_meta->delete_bitmap_ptr() : delete_bitmap;
482
4.26M
    for (size_t i = 0; i < specified_rowsets.size(); i++) {
483
4.25M
        const auto& rs = specified_rowsets[i];
484
4.25M
        std::vector<KeyBoundsPB> segments_key_bounds;
485
4.25M
        rs->rowset_meta()->get_segments_key_bounds(&segments_key_bounds);
486
4.25M
        int num_segments = cast_set<int>(rs->num_segments());
487
        // MOW lookup requires per-segment bounds. Aggregation must be disabled
488
        // for MOW writers, but enforce at runtime too — indexing segments_key_bounds[j]
489
        // below would be out-of-bounds otherwise.
490
4.25M
        if (UNLIKELY(rs->rowset_meta()->is_segments_key_bounds_aggregated() ||
491
4.25M
                     static_cast<int>(segments_key_bounds.size()) != num_segments)) {
492
0
            return Status::InternalError(
493
0
                    "MOW lookup got rowset with inconsistent segments_key_bounds, rowset_id={}, "
494
0
                    "aggregated={}, bounds_size={}, num_segments={}",
495
0
                    rs->rowset_id().to_string(),
496
0
                    rs->rowset_meta()->is_segments_key_bounds_aggregated(),
497
0
                    segments_key_bounds.size(), num_segments);
498
0
        }
499
4.25M
        std::vector<uint32_t> picked_segments;
500
8.25M
        for (int j = num_segments - 1; j >= 0; j--) {
501
4.00M
            if (_key_is_not_in_segment(key_without_seq, segments_key_bounds[j],
502
4.00M
                                       rs->rowset_meta()->is_segments_key_bounds_truncated())) {
503
308k
                continue;
504
308k
            }
505
3.69M
            picked_segments.emplace_back(j);
506
3.69M
        }
507
4.25M
        if (picked_segments.empty()) {
508
540k
            continue;
509
540k
        }
510
511
3.71M
        if (UNLIKELY(segment_caches[i] == nullptr)) {
512
28.7k
            segment_caches[i] = std::make_unique<SegmentCacheHandle>();
513
28.7k
            RETURN_IF_ERROR(SegmentLoader::instance()->load_segments(
514
28.7k
                    std::static_pointer_cast<BetaRowset>(rs), segment_caches[i].get(), true, true,
515
28.7k
                    stats, io_ctx));
516
28.7k
        }
517
3.71M
        auto& segments = segment_caches[i]->get_segments();
518
3.71M
        DCHECK_EQ(segments.size(), num_segments);
519
520
3.71M
        for (auto id : picked_segments) {
521
3.71M
            Status s = segments[id]->lookup_row_key(encoded_key, schema, with_seq_col, with_rowid,
522
3.71M
                                                    &loc, stats, encoded_seq_value, io_ctx);
523
3.71M
            if (s.is<KEY_NOT_FOUND>()) {
524
27.9k
                continue;
525
27.9k
            }
526
3.68M
            if (!s.ok() && !s.is<KEY_ALREADY_EXISTS>()) {
527
0
                return s;
528
0
            }
529
3.68M
            if (s.ok() && tablet_delete_bitmap->contains_agg_with_cache_if_eligible(
530
3.67M
                                  {loc.rowset_id, loc.segment_id, version}, loc.row_id)) {
531
                // if has sequence col, we continue to compare the sequence_id of
532
                // all rowsets, util we find an existing key.
533
354
                if (schema->has_sequence_col()) {
534
190
                    continue;
535
190
                }
536
                // The key is deleted, we don't need to search for it any more.
537
164
                break;
538
354
            }
539
            // `st` is either OK or KEY_ALREADY_EXISTS now.
540
            // for partial update, even if the key is already exists, we still need to
541
            // read it's original values to keep all columns align.
542
3.68M
            *row_location = loc;
543
3.68M
            if (rowset) {
544
                // return it's rowset
545
3.68M
                *rowset = rs;
546
3.68M
            }
547
3.68M
            TEST_SYNC_POINT_CALLBACK("BaseTablet::lookup_row_key:found", this, rs.get(),
548
3.68M
                                     with_seq_col, s.code());
549
            // find it and return
550
3.68M
            return s;
551
3.68M
        }
552
3.71M
    }
553
3.50k
    g_tablet_pk_not_found << 1;
554
3.50k
    return Status::Error<ErrorCode::KEY_NOT_FOUND>("can't find key in all rowsets");
555
3.68M
}
556
557
// if user pass a token, then all calculation works will submit to a threadpool,
558
// user can get all delete bitmaps from that token.
559
// if `token` is nullptr, the calculation will run in local, and user can get the result
560
// delete bitmap from `delete_bitmap` directly.
561
Status BaseTablet::calc_delete_bitmap(const BaseTabletSPtr& tablet, RowsetSharedPtr rowset,
562
                                      const std::vector<segment_v2::SegmentSharedPtr>& segments,
563
                                      const std::vector<RowsetSharedPtr>& specified_rowsets,
564
                                      DeleteBitmapPtr delete_bitmap, int64_t end_version,
565
                                      CalcDeleteBitmapToken* token, RowsetWriter* rowset_writer,
566
127k
                                      DeleteBitmapPtr tablet_delete_bitmap) {
567
127k
    if (specified_rowsets.empty() || segments.empty()) {
568
89.8k
        return Status::OK();
569
89.8k
    }
570
571
37.7k
    OlapStopWatch watch;
572
38.0k
    for (const auto& segment : segments) {
573
38.0k
        const auto& seg = segment;
574
38.0k
        if (token != nullptr) {
575
6.12k
            RETURN_IF_ERROR(token->submit(tablet, rowset, seg, specified_rowsets, end_version,
576
6.12k
                                          delete_bitmap, rowset_writer, tablet_delete_bitmap));
577
31.9k
        } else {
578
31.9k
            RETURN_IF_ERROR(tablet->calc_segment_delete_bitmap(
579
31.9k
                    rowset, segment, specified_rowsets, delete_bitmap, end_version, rowset_writer,
580
31.9k
                    tablet_delete_bitmap));
581
31.9k
        }
582
38.0k
    }
583
584
37.7k
    return Status::OK();
585
37.7k
}
586
587
Status BaseTablet::calc_segment_delete_bitmap(RowsetSharedPtr rowset,
588
                                              const segment_v2::SegmentSharedPtr& seg,
589
                                              const std::vector<RowsetSharedPtr>& specified_rowsets,
590
                                              DeleteBitmapPtr delete_bitmap, int64_t end_version,
591
                                              RowsetWriter* rowset_writer,
592
                                              DeleteBitmapPtr tablet_delete_bitmap,
593
38.1k
                                              int64_t queue_time_us) {
594
38.1k
    OlapStopWatch watch;
595
38.1k
    auto rowset_id = rowset->rowset_id();
596
38.1k
    Version dummy_version(end_version + 1, end_version + 1);
597
38.1k
    auto rowset_schema = rowset->tablet_schema();
598
599
38.1k
    PartialUpdateInfo* partial_update_info =
600
38.1k
            rowset_writer != nullptr ? rowset_writer->get_partial_update_info().get() : nullptr;
601
38.1k
    bool is_partial_update = partial_update_info && partial_update_info->is_partial_update();
602
38.1k
    bool need_rewrite_conflict = partial_update_info != nullptr;
603
    // `have_input_seq_column` is for fixed partial update only. For flexible partial update, we should use
604
    // the skip bitmap to determine wheather a row has specified the sequence column
605
38.1k
    bool have_input_seq_column = false;
606
    // `rids_be_overwritten` is for flexible partial update only, it records row ids that is overwritten by
607
    // another row with higher seqeucne value
608
38.1k
    std::set<uint32_t> rids_be_overwritten;
609
38.1k
    if (is_partial_update) {
610
109
        if (partial_update_info->is_fixed_partial_update() && rowset_schema->has_sequence_col()) {
611
4
            std::vector<uint32_t> including_cids =
612
4
                    rowset_writer->get_partial_update_info()->update_cids;
613
4
            have_input_seq_column =
614
4
                    rowset_schema->has_sequence_col() &&
615
4
                    (std::find(including_cids.cbegin(), including_cids.cend(),
616
4
                               rowset_schema->sequence_col_idx()) != including_cids.cend());
617
4
        }
618
109
    }
619
620
38.1k
    if (rowset_schema->num_variant_columns() > 0) {
621
        // During partial updates, the extracted columns of a variant should not be included in the rowset schema.
622
        // This is because the partial update for a variant needs to ignore the extracted columns.
623
        // Otherwise, the schema types in different rowsets might be inconsistent. When performing a partial update,
624
        // the complete variant is constructed by reading all the sub-columns of the variant.
625
4.24k
        rowset_schema = rowset_schema->copy_without_variant_extracted_columns();
626
4.24k
    }
627
    // use for partial update
628
38.1k
    FixedReadPlan read_plan_ori;
629
38.1k
    FixedReadPlan read_plan_update;
630
    // used to read sink-time LSN from input row-binlog rowset
631
38.1k
    FixedReadPlan read_plan_lsn;
632
38.1k
    RowsetSharedPtr row_binlog_rowset;
633
38.1k
    if (rowset_writer != nullptr) {
634
109
        if (auto* group_writer = typeid_cast<GroupRowsetWriter*>(rowset_writer);
635
109
            group_writer != nullptr) {
636
0
            auto& binlog_ctx =
637
0
                    const_cast<RowsetWriterContext&>(group_writer->row_binlog_writer()->context());
638
0
            if (binlog_ctx.write_binlog_opt().enable) {
639
0
                row_binlog_rowset = binlog_ctx.write_binlog_opt()
640
0
                                            .write_binlog_config()
641
0
                                            .source.row_binlog_rowset;
642
0
                DCHECK(row_binlog_rowset != nullptr);
643
0
            }
644
0
        }
645
109
    }
646
38.1k
    int64_t conflict_rows = 0;
647
38.1k
    int64_t new_generated_rows = 0;
648
649
38.1k
    std::map<RowsetId, RowsetSharedPtr> rsid_to_rowset;
650
38.1k
    rsid_to_rowset[rowset_id] = rowset;
651
38.1k
    Block block = rowset_schema->create_block();
652
38.1k
    Block ordered_block = block.clone_empty();
653
38.1k
    uint32_t pos = 0;
654
655
38.1k
    RETURN_IF_ERROR(seg->load_pk_index_and_bf(nullptr)); // We need index blocks to iterate
656
38.1k
    const auto* pk_idx = seg->get_primary_key_index();
657
38.1k
    int64_t total = pk_idx->num_rows();
658
38.1k
    uint32_t row_id = 0;
659
38.1k
    int64_t remaining = total;
660
38.1k
    bool exact_match = false;
661
38.1k
    std::string last_key;
662
38.1k
    int batch_size = 1024;
663
    // The data for each segment may be lookup multiple times. Creating a SegmentCacheHandle
664
    // will update the lru cache, and there will be obvious lock competition in multithreading
665
    // scenarios, so using a segment_caches to cache SegmentCacheHandle.
666
38.1k
    std::vector<std::unique_ptr<SegmentCacheHandle>> segment_caches(specified_rowsets.size());
667
79.3k
    while (remaining > 0) {
668
41.1k
        std::unique_ptr<segment_v2::IndexedColumnIterator> iter;
669
41.1k
        RETURN_IF_ERROR(pk_idx->new_iterator(&iter, nullptr));
670
671
41.1k
        size_t num_to_read = std::min<int64_t>(batch_size, remaining);
672
41.1k
        auto index_type = DataTypeFactory::instance().create_data_type(pk_idx->type(), 1, 0);
673
41.1k
        auto index_column = index_type->create_column();
674
41.1k
        Slice last_key_slice(last_key);
675
41.1k
        RETURN_IF_ERROR(iter->seek_at_or_after(&last_key_slice, &exact_match));
676
41.1k
        auto current_ordinal = iter->get_current_ordinal();
677
18.4E
        DCHECK(total == remaining + current_ordinal)
678
18.4E
                << "total: " << total << ", remaining: " << remaining
679
18.4E
                << ", current_ordinal: " << current_ordinal;
680
681
41.1k
        size_t num_read = num_to_read;
682
41.1k
        RETURN_IF_ERROR(iter->next_batch(&num_read, index_column));
683
18.4E
        DCHECK(num_to_read == num_read)
684
18.4E
                << "num_to_read: " << num_to_read << ", num_read: " << num_read;
685
41.1k
        last_key = index_column->get_data_at(num_read - 1).to_string();
686
687
        // exclude last_key, last_key will be read in next batch.
688
41.1k
        if (num_read == batch_size && num_read != remaining) {
689
3.42k
            num_read -= 1;
690
3.42k
        }
691
3.74M
        for (size_t i = 0; i < num_read; i++, row_id++) {
692
3.70M
            Slice key = Slice(index_column->get_data_at(i).data, index_column->get_data_at(i).size);
693
3.70M
            RowLocation loc;
694
            // calculate row id
695
3.70M
            if (!_tablet_meta->tablet_schema()->cluster_key_uids().empty()) {
696
66.2k
                size_t seq_col_length = 0;
697
66.2k
                if (_tablet_meta->tablet_schema()->has_sequence_col()) {
698
11.9k
                    seq_col_length =
699
11.9k
                            _tablet_meta->tablet_schema()
700
11.9k
                                    ->column(_tablet_meta->tablet_schema()->sequence_col_idx())
701
11.9k
                                    .length() +
702
11.9k
                            1;
703
11.9k
                }
704
66.2k
                size_t rowid_length = PrimaryKeyIndexReader::ROW_ID_LENGTH;
705
66.2k
                Slice key_without_seq =
706
66.2k
                        Slice(key.get_data(), key.get_size() - seq_col_length - rowid_length);
707
66.2k
                Slice rowid_slice =
708
66.2k
                        Slice(key.get_data() + key_without_seq.get_size() + seq_col_length + 1,
709
66.2k
                              rowid_length - 1);
710
66.2k
                const auto* rowid_coder = get_key_coder(FieldType::OLAP_FIELD_TYPE_UNSIGNED_INT);
711
66.2k
                RETURN_IF_ERROR(rowid_coder->decode_ascending(&rowid_slice, rowid_length,
712
66.2k
                                                              (uint8_t*)&row_id));
713
66.2k
            }
714
            // same row in segments should be filtered
715
3.70M
            if (delete_bitmap->contains({rowset_id, seg->id(), DeleteBitmap::TEMP_VERSION_COMMON},
716
3.70M
                                        row_id)) {
717
4
                continue;
718
4
            }
719
720
3.70M
            DBUG_EXECUTE_IF("BaseTablet::calc_segment_delete_bitmap.inject_err", {
721
3.70M
                auto p = dp->param("percent", 0.01);
722
3.70M
                std::mt19937 gen {std::random_device {}()};
723
3.70M
                std::bernoulli_distribution inject_fault {p};
724
3.70M
                if (inject_fault(gen)) {
725
3.70M
                    return Status::InternalError(
726
3.70M
                            "injection error in calc_segment_delete_bitmap, "
727
3.70M
                            "tablet_id={}, rowset_id={}",
728
3.70M
                            tablet_id(), rowset_id.to_string());
729
3.70M
                }
730
3.70M
            });
731
732
3.70M
            RowsetSharedPtr rowset_find;
733
3.70M
            Status st = Status::OK();
734
3.70M
            if (tablet_delete_bitmap == nullptr) {
735
2.21M
                st = lookup_row_key(key, rowset_schema.get(), true, specified_rowsets, &loc,
736
2.21M
                                    dummy_version.first - 1, segment_caches, &rowset_find);
737
2.21M
            } else {
738
1.49M
                st = lookup_row_key(key, rowset_schema.get(), true, specified_rowsets, &loc,
739
1.49M
                                    dummy_version.first - 1, segment_caches, &rowset_find, true,
740
1.49M
                                    nullptr, nullptr, tablet_delete_bitmap);
741
1.49M
            }
742
3.70M
            bool expected_st = st.ok() || st.is<KEY_NOT_FOUND>() || st.is<KEY_ALREADY_EXISTS>();
743
            // It's a defensive DCHECK, we need to exclude some common errors to avoid core-dump
744
            // while stress test
745
3.70M
            DCHECK(expected_st || st.is<MEM_LIMIT_EXCEEDED>())
746
6.07k
                    << "unexpected error status while lookup_row_key:" << st;
747
3.70M
            if (!expected_st) {
748
0
                return st;
749
0
            }
750
3.70M
            if (st.is<KEY_NOT_FOUND>()) {
751
48.8k
                continue;
752
48.8k
            }
753
754
3.65M
            ++conflict_rows;
755
3.65M
            if (st.is<KEY_ALREADY_EXISTS>() &&
756
3.65M
                (!is_partial_update ||
757
296
                 (partial_update_info->is_fixed_partial_update() && have_input_seq_column))) {
758
                // `st.is<KEY_ALREADY_EXISTS>()` means that there exists a row with the same key and larger value
759
                // in seqeunce column.
760
                // - If the current load is not a partial update, we just delete current row.
761
                // - Otherwise, it means that we are doing the alignment process in publish phase due to conflicts
762
                // during concurrent partial updates. And there exists another load which introduces a row with
763
                // the same keys and larger sequence column value published successfully after the commit phase
764
                // of the current load.
765
                //     - If the columns we update include sequence column, we should delete the current row becase the
766
                //       partial update on the current row has been `overwritten` by the previous one with larger sequence
767
                //       column value.
768
                //     - Otherwise, we should combine the values of the missing columns in the previous row and the values
769
                //       of the including columns in the current row into a new row.
770
286
                delete_bitmap->add({rowset_id, seg->id(), DeleteBitmap::TEMP_VERSION_COMMON},
771
286
                                   row_id);
772
286
                continue;
773
                // NOTE: for partial update which doesn't specify the sequence column, we can't use the sequence column value filled in flush phase
774
                // as its final value. Otherwise it may cause inconsistency between replicas.
775
286
            }
776
3.65M
            if (need_rewrite_conflict) {
777
                // In publish version, record rows to be deleted for concurrent update
778
                // For example, if version 5 and 6 update a row, but version 6 only see
779
                // version 4 when write, and when publish version, version 5's value will
780
                // be marked as deleted and it's update is losed.
781
                // So here we should read version 5's columns and build a new row, which is
782
                // consists of version 6's update columns and version 5's origin columns
783
                // here we build 2 read plan for ori values and update values
784
785
                // - for fixed partial update, we should read update columns from current load's rowset
786
                // and read missing columns from previous rowsets to create the final block
787
                // - for flexible partial update, we should read all columns from current load's rowset
788
                // and read non sort key columns from previous rowsets to create the final block
789
                // - for upsert rewrite, we should read all columns from current load's rowset
790
                // So we only need to record rows to read for both mode partial update and upsert rewrite
791
84
                if (is_partial_update) {
792
84
                    read_plan_ori.prepare_to_read(loc, pos);
793
84
                }
794
84
                read_plan_update.prepare_to_read(RowLocation {rowset_id, seg->id(), row_id}, pos);
795
84
                if (row_binlog_rowset != nullptr) {
796
0
                    read_plan_lsn.prepare_to_read(
797
0
                            RowLocation {row_binlog_rowset->rowset_id(), seg->id(), row_id}, pos);
798
0
                }
799
800
                // For flexible partial update, we should use skip bitmap to determine wheather
801
                // a row has specified the sequence column. But skip bitmap should be read from the segment.
802
                // So we record these row ids and process and filter them in `generate_new_block_for_flexible_partial_update()`
803
84
                if (st.is<KEY_ALREADY_EXISTS>() &&
804
84
                    partial_update_info->is_flexible_partial_update()) {
805
0
                    rids_be_overwritten.insert(pos);
806
0
                }
807
808
84
                rsid_to_rowset[rowset_find->rowset_id()] = rowset_find;
809
84
                ++pos;
810
811
                // delete bitmap will be calculate when memtable flush and
812
                // publish. The two stages may see different versions.
813
                // When there is sequence column, the currently imported data
814
                // of rowset may be marked for deletion at memtablet flush or
815
                // publish because the seq column is smaller than the previous
816
                // rowset.
817
                // just set 0 as a unified temporary version number, and update to
818
                // the real version number later.
819
84
                delete_bitmap->add(
820
84
                        {loc.rowset_id, loc.segment_id, DeleteBitmap::TEMP_VERSION_COMMON},
821
84
                        loc.row_id);
822
84
                delete_bitmap->add({rowset_id, seg->id(), DeleteBitmap::TEMP_VERSION_COMMON},
823
84
                                   row_id);
824
84
                ++new_generated_rows;
825
84
                continue;
826
84
            }
827
            // when st = ok
828
3.65M
            delete_bitmap->add({loc.rowset_id, loc.segment_id, DeleteBitmap::TEMP_VERSION_COMMON},
829
3.65M
                               loc.row_id);
830
3.65M
        }
831
41.1k
        remaining -= num_read;
832
41.1k
    }
833
    // DCHECK_EQ(total, row_id) << "segment total rows: " << total << " row_id:" << row_id;
834
835
38.1k
    if (config::enable_merge_on_write_correctness_check) {
836
38.0k
        RowsetIdUnorderedSet rowsetids;
837
295k
        for (const auto& specified_rowset : specified_rowsets) {
838
295k
            rowsetids.emplace(specified_rowset->rowset_id());
839
295k
            VLOG_NOTICE << "[tabletID:" << tablet_id() << "]"
840
136
                        << "[add_sentinel_mark_to_delete_bitmap][end_version:" << end_version << "]"
841
136
                        << "add:" << specified_rowset->rowset_id();
842
295k
        }
843
38.0k
        add_sentinel_mark_to_delete_bitmap(delete_bitmap.get(), rowsetids);
844
38.0k
    }
845
846
38.1k
    if (pos > 0) {
847
20
        DCHECK(partial_update_info != nullptr);
848
20
        if (partial_update_info->is_flexible_partial_update()) {
849
0
            RETURN_IF_ERROR(generate_new_block_for_flexible_partial_update(
850
0
                    rowset_schema, partial_update_info, rids_be_overwritten, read_plan_ori,
851
0
                    read_plan_update, rsid_to_rowset, &block));
852
20
        } else {
853
20
            RETURN_IF_ERROR(generate_new_block_for_partial_update(
854
20
                    rowset_schema, partial_update_info, read_plan_ori, read_plan_update,
855
20
                    rsid_to_rowset, &block));
856
20
        }
857
858
        // read sink-time LSN from input row-binlog rowset, aligned with `block` rows.
859
20
        Block lsn_block;
860
20
        if (row_binlog_rowset != nullptr) {
861
0
            auto row_binlog_schema = row_binlog_rowset->tablet_schema();
862
0
            std::vector<uint32_t> lsn_cids = {
863
0
                    static_cast<uint32_t>(row_binlog_schema->binlog_lsn_col_idx())};
864
0
            lsn_block = row_binlog_schema->create_block_by_cids(lsn_cids);
865
0
            std::map<RowsetId, RowsetSharedPtr> rsid_to_row_binlog {
866
0
                    {row_binlog_rowset->rowset_id(), row_binlog_rowset}};
867
0
            std::map<uint32_t, uint32_t> read_index;
868
0
            RETURN_IF_ERROR(read_plan_lsn.read_columns_by_plan(*row_binlog_schema, lsn_cids,
869
0
                                                               rsid_to_row_binlog, lsn_block,
870
0
                                                               &read_index, false));
871
0
        }
872
873
20
        std::vector<uint32_t> sort_perm;
874
20
        RETURN_IF_ERROR(sort_block(block, ordered_block, &sort_perm));
875
20
        auto segment_id = rowset_writer->allocate_segment_id();
876
877
        // Publish-phase partial update may flush transient segments to a GroupRowsetWriter.
878
        // For row-binlog writing, RowBinlogSegmentWriter requires `seg_id -> lsn_ids` to be
879
        // registered before the segment writer is constructed.
880
20
        if (auto* group_writer = typeid_cast<GroupRowsetWriter*>(rowset_writer);
881
20
            group_writer != nullptr) {
882
0
            auto binlog_writer = group_writer->row_binlog_writer();
883
0
            auto& binlog_ctx = const_cast<RowsetWriterContext&>(binlog_writer->context());
884
0
            if (binlog_ctx.write_binlog_opt().enable) {
885
0
                const auto& src =
886
0
                        assert_cast<const ColumnInt64&>(*lsn_block.get_by_position(0).column);
887
0
                auto lsn_ids = std::make_shared<std::vector<int64_t>>();
888
0
                lsn_ids->reserve(sort_perm.size());
889
0
                for (auto p : sort_perm) {
890
0
                    lsn_ids->emplace_back(src.get_data()[p]);
891
0
                }
892
0
                binlog_ctx.write_binlog_opt().write_binlog_config().insert_seg_lsn(
893
0
                        segment_id, std::move(lsn_ids));
894
0
            }
895
0
        }
896
20
        RETURN_IF_ERROR(rowset_writer->flush_single_block(&ordered_block, segment_id));
897
20
        auto cost_us = watch.get_elapse_time_us();
898
20
        if (config::enable_mow_verbose_log || cost_us > 10 * 1000 || queue_time_us > 10 * 1000) {
899
19
            LOG(INFO) << "calc segment delete bitmap for "
900
19
                      << partial_update_info->partial_update_mode_str()
901
19
                      << ", tablet: " << tablet_id() << " rowset: " << rowset_id
902
19
                      << " seg_id: " << seg->id() << " dummy_version: " << end_version + 1
903
19
                      << " rows: " << seg->num_rows() << " conflict rows: " << conflict_rows
904
19
                      << " new generated rows: " << new_generated_rows
905
19
                      << " bitmap num: " << delete_bitmap->get_delete_bitmap_count()
906
19
                      << " bitmap cardinality: " << delete_bitmap->cardinality()
907
19
                      << " queue_time_us: " << queue_time_us << ", cost: " << cost_us << "(us)";
908
19
        }
909
20
        return Status::OK();
910
20
    }
911
38.1k
    auto cost_us = watch.get_elapse_time_us();
912
38.1k
    if (config::enable_mow_verbose_log || cost_us > 10 * 1000 || queue_time_us > 10 * 1000) {
913
3.88k
        LOG(INFO) << "calc segment delete bitmap, tablet: " << tablet_id()
914
3.88k
                  << " rowset: " << rowset_id << " seg_id: " << seg->id()
915
3.88k
                  << " dummy_version: " << end_version + 1 << " rows: " << seg->num_rows()
916
3.88k
                  << " conflict rows: " << conflict_rows
917
3.88k
                  << " bitmap num: " << delete_bitmap->get_delete_bitmap_count()
918
3.88k
                  << " bitmap cardinality: " << delete_bitmap->cardinality()
919
3.88k
                  << " queue_time_us: " << queue_time_us << ", cost: " << cost_us << "(us)";
920
3.88k
    }
921
38.1k
    return Status::OK();
922
38.1k
}
923
924
Status BaseTablet::sort_block(Block& in_block, Block& output_block,
925
20
                              std::vector<uint32_t>* permutation) {
926
20
    ScopedMutableBlock scoped_input_block(&in_block);
927
20
    auto& mutable_input_block = scoped_input_block.mutable_block();
928
20
    ScopedMutableBlock scoped_output_block(&output_block);
929
20
    auto& mutable_output_block = scoped_output_block.mutable_block();
930
931
20
    std::shared_ptr<RowInBlockComparator> vec_row_comparator =
932
20
            std::make_shared<RowInBlockComparator>(_tablet_meta->tablet_schema());
933
20
    vec_row_comparator->set_block(&mutable_input_block);
934
935
20
    std::vector<std::unique_ptr<RowInBlock>> row_in_blocks;
936
20
    const auto input_rows = mutable_input_block.rows();
937
20
    DCHECK(input_rows <= std::numeric_limits<int>::max());
938
20
    row_in_blocks.reserve(input_rows);
939
104
    for (size_t i = 0; i < input_rows; ++i) {
940
84
        row_in_blocks.emplace_back(std::make_unique<RowInBlock>(i));
941
84
    }
942
20
    std::sort(row_in_blocks.begin(), row_in_blocks.end(),
943
20
              [&](const std::unique_ptr<RowInBlock>& l,
944
128
                  const std::unique_ptr<RowInBlock>& r) -> bool {
945
128
                  auto value = (*vec_row_comparator)(l.get(), r.get());
946
128
                  DCHECK(value != 0) << "value equel when sort block, l_pos: " << l->_row_pos
947
0
                                     << " r_pos: " << r->_row_pos;
948
128
                  return value < 0;
949
128
              });
950
20
    std::vector<uint32_t> row_pos_vec;
951
20
    row_pos_vec.reserve(input_rows);
952
84
    for (auto& block : row_in_blocks) {
953
84
        row_pos_vec.emplace_back(block->_row_pos);
954
84
    }
955
20
    scoped_input_block.restore();
956
20
    RETURN_IF_ERROR(mutable_output_block.add_rows(&in_block, row_pos_vec.data(),
957
20
                                                  row_pos_vec.data() + input_rows));
958
20
    if (permutation != nullptr) {
959
20
        *permutation = std::move(row_pos_vec);
960
20
    }
961
20
    return Status::OK();
962
20
}
963
964
// fetch value by row column
965
Status BaseTablet::fetch_value_through_row_column(RowsetSharedPtr input_rowset,
966
                                                  const TabletSchema& tablet_schema, uint32_t segid,
967
                                                  const std::vector<uint32_t>& rowids,
968
353
                                                  const std::vector<uint32_t>& cids, Block& block) {
969
353
    MonotonicStopWatch watch;
970
353
    watch.start();
971
353
    Defer _defer([&]() {
972
352
        LOG_EVERY_N(INFO, 500) << "fetch_value_by_rowids, cost(us):" << watch.elapsed_time() / 1000
973
2
                               << ", row_batch_size:" << rowids.size();
974
352
    });
975
976
353
    BetaRowsetSharedPtr rowset = std::static_pointer_cast<BetaRowset>(input_rowset);
977
353
    CHECK(rowset);
978
353
    CHECK(tablet_schema.has_row_store_for_all_columns());
979
353
    SegmentCacheHandle segment_cache_handle;
980
353
    std::unique_ptr<segment_v2::ColumnIterator> column_iterator;
981
353
    OlapReaderStatistics stats;
982
353
    const auto& column = *DORIS_TRY(tablet_schema.column(BeConsts::ROW_STORE_COL));
983
353
    RETURN_IF_ERROR(_get_segment_column_iterator(rowset, segid, column, &segment_cache_handle,
984
353
                                                 &column_iterator, &stats));
985
    // get and parse tuple row
986
353
    MutableColumnPtr column_ptr = ColumnString::create();
987
353
    RETURN_IF_ERROR(column_iterator->read_by_rowids(rowids.data(), rowids.size(), column_ptr));
988
353
    assert(column_ptr->size() == rowids.size());
989
353
    auto* string_column = static_cast<ColumnString*>(column_ptr.get());
990
353
    DataTypeSerDeSPtrs serdes;
991
353
    serdes.resize(cids.size());
992
353
    std::unordered_map<uint32_t, uint32_t> col_uid_to_idx;
993
353
    std::vector<std::string> default_values;
994
353
    default_values.resize(cids.size());
995
3.82k
    for (int i = 0; i < cids.size(); ++i) {
996
3.47k
        const TabletColumn& tablet_column = tablet_schema.column(cids[i]);
997
3.47k
        DataTypePtr type = DataTypeFactory::instance().create_data_type(tablet_column);
998
3.47k
        col_uid_to_idx[tablet_column.unique_id()] = i;
999
3.47k
        default_values[i] = tablet_column.default_value();
1000
3.47k
        serdes[i] = type->get_serde();
1001
3.47k
    }
1002
353
    RETURN_IF_ERROR(JsonbSerializeUtil::jsonb_to_block(serdes, *string_column, col_uid_to_idx,
1003
353
                                                       block, default_values, {}));
1004
353
    return Status::OK();
1005
353
}
1006
1007
Status BaseTablet::fetch_value_by_rowids(RowsetSharedPtr input_rowset, uint32_t segid,
1008
                                         const std::vector<uint32_t>& rowids,
1009
3.77k
                                         const TabletColumn& tablet_column, MutableColumnPtr& dst) {
1010
3.77k
    MonotonicStopWatch watch;
1011
3.77k
    watch.start();
1012
3.77k
    Defer _defer([&]() {
1013
3.76k
        LOG_EVERY_N(INFO, 500) << "fetch_value_by_rowids, cost(us):" << watch.elapsed_time() / 1000
1014
11
                               << ", row_batch_size:" << rowids.size();
1015
3.76k
    });
1016
1017
    // read row data
1018
3.77k
    BetaRowsetSharedPtr rowset = std::static_pointer_cast<BetaRowset>(input_rowset);
1019
3.77k
    CHECK(rowset);
1020
3.77k
    SegmentCacheHandle segment_cache_handle;
1021
3.77k
    std::unique_ptr<segment_v2::ColumnIterator> column_iterator;
1022
3.77k
    OlapReaderStatistics stats;
1023
3.77k
    RETURN_IF_ERROR(_get_segment_column_iterator(rowset, segid, tablet_column,
1024
3.77k
                                                 &segment_cache_handle, &column_iterator, &stats));
1025
3.77k
    RETURN_IF_ERROR(column_iterator->read_by_rowids(rowids.data(), rowids.size(), dst));
1026
3.77k
    return Status::OK();
1027
3.77k
}
1028
1029
const signed char* BaseTablet::get_delete_sign_column_data(const Block& block,
1030
3.97k
                                                           size_t rows_at_least) {
1031
3.97k
    if (int pos = block.get_position_by_name(DELETE_SIGN); pos != -1) {
1032
3.95k
        const ColumnWithTypeAndName& delete_sign_column = block.get_by_position(pos);
1033
3.95k
        const auto& delete_sign_col = assert_cast<const ColumnInt8&>(*(delete_sign_column.column));
1034
3.95k
        if (delete_sign_col.size() >= rows_at_least) {
1035
3.37k
            return delete_sign_col.get_data().data();
1036
3.37k
        }
1037
3.95k
    }
1038
597
    return nullptr;
1039
3.97k
};
1040
1041
Status BaseTablet::generate_default_value_block(const TabletSchema& schema,
1042
                                                const std::vector<uint32_t>& cids,
1043
                                                const std::vector<std::string>& default_values,
1044
                                                const Block& ref_block,
1045
1.81k
                                                Block& default_value_block) {
1046
1.81k
    auto mutable_default_value_columns_guard = default_value_block.mutate_columns_scoped();
1047
1.81k
    auto& mutable_default_value_columns = mutable_default_value_columns_guard.mutable_columns();
1048
13.7k
    for (auto i = 0; i < cids.size(); ++i) {
1049
11.9k
        const auto& column = schema.column(cids[i]);
1050
11.9k
        if (column.has_default_value()) {
1051
4.09k
            const auto& default_value = default_values[i];
1052
4.09k
            StringRef str(default_value);
1053
4.09k
            RETURN_IF_ERROR(ref_block.get_by_position(i).type->get_serde()->default_from_string(
1054
4.09k
                    str, *mutable_default_value_columns[i]));
1055
4.09k
        }
1056
11.9k
    }
1057
1.81k
    return Status::OK();
1058
1.81k
}
1059
1060
Status BaseTablet::generate_new_block_for_partial_update(
1061
        TabletSchemaSPtr rowset_schema, const PartialUpdateInfo* partial_update_info,
1062
        const FixedReadPlan& read_plan_ori, const FixedReadPlan& read_plan_update,
1063
20
        const std::map<RowsetId, RowsetSharedPtr>& rsid_to_rowset, Block* output_block) {
1064
    // do partial update related works
1065
    // 1. read columns by read plan
1066
    // 2. generate new block
1067
    // 3. write a new segment and modify rowset meta
1068
    // 4. mark current keys deleted
1069
20
    CHECK(output_block);
1070
20
    auto full_mutable_columns_guard = output_block->mutate_columns_scoped();
1071
20
    auto& full_mutable_columns = full_mutable_columns_guard.mutable_columns();
1072
20
    const auto& missing_cids = partial_update_info->missing_cids;
1073
20
    const auto& update_cids = partial_update_info->update_cids;
1074
20
    auto old_block = rowset_schema->create_block_by_cids(missing_cids);
1075
20
    auto update_block = rowset_schema->create_block_by_cids(update_cids);
1076
1077
20
    bool have_input_seq_column = false;
1078
20
    if (rowset_schema->has_sequence_col()) {
1079
4
        have_input_seq_column =
1080
4
                (std::find(update_cids.cbegin(), update_cids.cend(),
1081
4
                           rowset_schema->sequence_col_idx()) != update_cids.cend());
1082
4
    }
1083
1084
    // rowid in the final block(start from 0, increase continuously) -> rowid to read in update_block
1085
20
    std::map<uint32_t, uint32_t> read_index_update;
1086
1087
    // read current rowset first, if a row in the current rowset has delete sign mark
1088
    // we don't need to read values from old block
1089
20
    RETURN_IF_ERROR(read_plan_update.read_columns_by_plan(
1090
20
            *rowset_schema, update_cids, rsid_to_rowset, update_block, &read_index_update, false));
1091
20
    size_t update_rows = read_index_update.size();
1092
72
    for (auto i = 0; i < update_cids.size(); ++i) {
1093
256
        for (auto idx = 0; idx < update_rows; ++idx) {
1094
204
            full_mutable_columns[update_cids[i]]->insert_from(
1095
204
                    *update_block.get_by_position(i).column, read_index_update[idx]);
1096
204
        }
1097
52
    }
1098
1099
    // if there is sequence column in the table, we need to read the sequence column,
1100
    // otherwise it may cause the merge-on-read based compaction policy to produce incorrect results
1101
20
    const auto* __restrict new_block_delete_signs =
1102
20
            rowset_schema->has_sequence_col()
1103
20
                    ? nullptr
1104
20
                    : get_delete_sign_column_data(update_block, update_rows);
1105
1106
    // rowid in the final block(start from 0, increase, may not continuous becasue we skip to read some rows) -> rowid to read in old_block
1107
20
    std::map<uint32_t, uint32_t> read_index_old;
1108
20
    RETURN_IF_ERROR(read_plan_ori.read_columns_by_plan(*rowset_schema, missing_cids, rsid_to_rowset,
1109
20
                                                       old_block, &read_index_old, true,
1110
20
                                                       new_block_delete_signs));
1111
20
    size_t old_rows = read_index_old.size();
1112
20
    const auto* __restrict old_block_delete_signs =
1113
20
            get_delete_sign_column_data(old_block, old_rows);
1114
20
    DCHECK(old_block_delete_signs != nullptr);
1115
    // build default value block
1116
20
    auto default_value_block = old_block.clone_empty();
1117
20
    RETURN_IF_ERROR(BaseTablet::generate_default_value_block(*rowset_schema, missing_cids,
1118
20
                                                             partial_update_info->default_values,
1119
20
                                                             old_block, default_value_block));
1120
1121
20
    CHECK(update_rows >= old_rows);
1122
1123
    // build full block
1124
132
    for (auto i = 0; i < missing_cids.size(); ++i) {
1125
112
        const auto& rs_column = rowset_schema->column(missing_cids[i]);
1126
112
        auto& mutable_column = full_mutable_columns[missing_cids[i]];
1127
596
        for (auto idx = 0; idx < update_rows; ++idx) {
1128
            // There are two cases we don't need to read values from old data:
1129
            //     1. if the conflicting new row's delete sign is marked, which means the value columns
1130
            //     of the row will not be read. So we don't need to read the missing values from the previous rows.
1131
            //     2. if the conflicting old row's delete sign is marked, which means that the key is not exist now,
1132
            //     we should not read old values from the deleted data, and should use default value instead.
1133
            //     NOTE: since now we are in the publishing phase, all data is commited
1134
            //         before, even the `strict_mode` is true (which requires partial update
1135
            //         load job can't insert new keys), this "new" key MUST be written into
1136
            //         the new generated segment file.
1137
484
            bool new_row_delete_sign =
1138
484
                    (new_block_delete_signs != nullptr && new_block_delete_signs[idx]);
1139
484
            if (new_row_delete_sign) {
1140
27
                mutable_column->insert_default();
1141
457
            } else {
1142
457
                bool use_default = false;
1143
457
                bool old_row_delete_sign = (old_block_delete_signs != nullptr &&
1144
457
                                            old_block_delete_signs[read_index_old.at(idx)] != 0);
1145
457
                if (old_row_delete_sign) {
1146
15
                    if (!rowset_schema->has_sequence_col()) {
1147
15
                        use_default = true;
1148
15
                    } else if (have_input_seq_column || !rs_column.is_seqeunce_col()) {
1149
                        // to keep the sequence column value not decreasing, we should read values of seq column
1150
                        // from old rows even if the old row is deleted when the input don't specify the sequence column, otherwise
1151
                        // it may cause the merge-on-read based compaction to produce incorrect results
1152
0
                        use_default = true;
1153
0
                    }
1154
15
                }
1155
1156
457
                if (use_default) {
1157
15
                    if (rs_column.has_default_value()) {
1158
6
                        mutable_column->insert_from(*default_value_block.get_by_position(i).column,
1159
6
                                                    0);
1160
9
                    } else if (rs_column.is_nullable()) {
1161
9
                        assert_cast<ColumnNullable*, TypeCheckOnRelease::DISABLE>(
1162
9
                                mutable_column.get())
1163
9
                                ->insert_default();
1164
9
                    } else {
1165
0
                        mutable_column->insert_default();
1166
0
                    }
1167
442
                } else {
1168
442
                    mutable_column->insert_from(*old_block.get_by_position(i).column,
1169
442
                                                read_index_old[idx]);
1170
442
                }
1171
457
            }
1172
484
        }
1173
112
    }
1174
20
    full_mutable_columns_guard.restore();
1175
20
    VLOG_DEBUG << "full block when publish: " << output_block->dump_data();
1176
20
    return Status::OK();
1177
20
}
1178
1179
static void fill_cell_for_flexible_partial_update(
1180
        std::map<uint32_t, uint32_t>& read_index_old,
1181
        std::map<uint32_t, uint32_t>& read_index_update, const TabletSchemaSPtr& rowset_schema,
1182
        const PartialUpdateInfo* partial_update_info, const TabletColumn& tablet_column,
1183
        std::size_t idx, MutableColumnPtr& new_col, const IColumn& default_value_col,
1184
        const IColumn& old_value_col, const IColumn& cur_col, bool skipped,
1185
0
        bool row_has_sequence_col, const signed char* delete_sign_column_data) {
1186
0
    if (skipped) {
1187
0
        bool use_default = false;
1188
0
        bool old_row_delete_sign =
1189
0
                (delete_sign_column_data != nullptr &&
1190
0
                 delete_sign_column_data[read_index_old[cast_set<uint32_t>(idx)]] != 0);
1191
0
        if (old_row_delete_sign) {
1192
0
            if (!rowset_schema->has_sequence_col()) {
1193
0
                use_default = true;
1194
0
            } else if (row_has_sequence_col || (!tablet_column.is_seqeunce_col() &&
1195
0
                                                (tablet_column.unique_id() !=
1196
0
                                                 partial_update_info->sequence_map_col_uid()))) {
1197
                // to keep the sequence column value not decreasing, we should read values of seq column(and seq map column)
1198
                // from old rows even if the old row is deleted when the input don't specify the sequence column, otherwise
1199
                // it may cause the merge-on-read based compaction to produce incorrect results
1200
0
                use_default = true;
1201
0
            }
1202
0
        }
1203
0
        if (use_default) {
1204
0
            if (tablet_column.has_default_value()) {
1205
0
                new_col->insert_from(default_value_col, 0);
1206
0
            } else if (tablet_column.is_nullable()) {
1207
0
                assert_cast<ColumnNullable*, TypeCheckOnRelease::DISABLE>(new_col.get())
1208
0
                        ->insert_many_defaults(1);
1209
0
            } else if (tablet_column.is_auto_increment()) {
1210
                // For auto-increment column, its default value(generated value) is filled in current block in flush phase
1211
                // when the load doesn't specify the auto-increment column
1212
                //     - if the previous conflicting row is deleted, we should use the value in current block as its final value
1213
                //     - if the previous conflicting row is an insert, we should use the value in old block as its final value to
1214
                //       keep consistency between replicas
1215
0
                new_col->insert_from(cur_col, read_index_update[cast_set<uint32_t>(idx)]);
1216
0
            } else {
1217
0
                new_col->insert_default();
1218
0
            }
1219
0
        } else {
1220
0
            new_col->insert_from(old_value_col, read_index_old[cast_set<uint32_t>(idx)]);
1221
0
        }
1222
0
    } else {
1223
0
        new_col->insert_from(cur_col, read_index_update[cast_set<uint32_t>(idx)]);
1224
0
    }
1225
0
}
1226
1227
Status BaseTablet::generate_new_block_for_flexible_partial_update(
1228
        TabletSchemaSPtr rowset_schema, const PartialUpdateInfo* partial_update_info,
1229
        std::set<uint32_t>& rids_be_overwritten, const FixedReadPlan& read_plan_ori,
1230
        const FixedReadPlan& read_plan_update,
1231
0
        const std::map<RowsetId, RowsetSharedPtr>& rsid_to_rowset, Block* output_block) {
1232
0
    CHECK(output_block);
1233
1234
0
    int32_t seq_col_unique_id = -1;
1235
0
    if (rowset_schema->has_sequence_col()) {
1236
0
        seq_col_unique_id = rowset_schema->column(rowset_schema->sequence_col_idx()).unique_id();
1237
0
    }
1238
0
    const auto& non_sort_key_cids = partial_update_info->missing_cids;
1239
0
    std::vector<uint32_t> all_cids(rowset_schema->num_columns());
1240
0
    std::iota(all_cids.begin(), all_cids.end(), 0);
1241
0
    auto old_block = rowset_schema->create_block_by_cids(non_sort_key_cids);
1242
0
    auto update_block = rowset_schema->create_block_by_cids(all_cids);
1243
1244
    // rowid in the final block(start from 0, increase continuously) -> rowid to read in update_block
1245
0
    std::map<uint32_t, uint32_t> read_index_update;
1246
1247
    // 1. read the current rowset first, if a row in the current rowset has delete sign mark
1248
    // we don't need to read values from old block for that row
1249
0
    RETURN_IF_ERROR(read_plan_update.read_columns_by_plan(*rowset_schema, all_cids, rsid_to_rowset,
1250
0
                                                          update_block, &read_index_update, true));
1251
0
    size_t update_rows = read_index_update.size();
1252
1253
    // TODO(bobhan1): add the delete sign optimazation here
1254
    // // if there is sequence column in the table, we need to read the sequence column,
1255
    // // otherwise it may cause the merge-on-read based compaction policy to produce incorrect results
1256
    // const auto* __restrict new_block_delete_signs =
1257
    //         rowset_schema->has_sequence_col()
1258
    //                 ? nullptr
1259
    //                 : get_delete_sign_column_data(update_block, update_rows);
1260
1261
    // 2. read previous rowsets
1262
    // rowid in the final block(start from 0, increase, may not continuous becasue we skip to read some rows) -> rowid to read in old_block
1263
0
    std::map<uint32_t, uint32_t> read_index_old;
1264
0
    RETURN_IF_ERROR(read_plan_ori.read_columns_by_plan(
1265
0
            *rowset_schema, non_sort_key_cids, rsid_to_rowset, old_block, &read_index_old, true));
1266
0
    size_t old_rows = read_index_old.size();
1267
0
    DCHECK(update_rows == old_rows);
1268
0
    const auto* __restrict old_block_delete_signs =
1269
0
            get_delete_sign_column_data(old_block, old_rows);
1270
0
    DCHECK(old_block_delete_signs != nullptr);
1271
1272
    // 3. build default value block
1273
0
    auto default_value_block = old_block.clone_empty();
1274
0
    RETURN_IF_ERROR(BaseTablet::generate_default_value_block(*rowset_schema, non_sort_key_cids,
1275
0
                                                             partial_update_info->default_values,
1276
0
                                                             old_block, default_value_block));
1277
1278
    // 4. build the final block
1279
0
    auto full_mutable_columns_guard = output_block->mutate_columns_scoped();
1280
0
    auto& full_mutable_columns = full_mutable_columns_guard.mutable_columns();
1281
0
    DCHECK(rowset_schema->has_skip_bitmap_col());
1282
0
    auto skip_bitmap_col_idx = rowset_schema->skip_bitmap_col_idx();
1283
0
    const std::vector<BitmapValue>* skip_bitmaps =
1284
0
            &(assert_cast<const ColumnBitmap*, TypeCheckOnRelease::DISABLE>(
1285
0
                      update_block.get_by_position(skip_bitmap_col_idx).column->get_ptr().get())
1286
0
                      ->get_data());
1287
1288
0
    if (rowset_schema->has_sequence_col() && !rids_be_overwritten.empty()) {
1289
        // If the row specifies the sequence column, we should delete the current row becase the
1290
        // flexible partial update on the current row has been `overwritten` by the previous one with larger sequence
1291
        // column value.
1292
0
        for (auto it = rids_be_overwritten.begin(); it != rids_be_overwritten.end();) {
1293
0
            auto rid = *it;
1294
0
            if (!skip_bitmaps->at(rid).contains(seq_col_unique_id)) {
1295
0
                ++it;
1296
0
            } else {
1297
0
                it = rids_be_overwritten.erase(it);
1298
0
            }
1299
0
        }
1300
0
    }
1301
1302
0
    for (std::size_t cid {0}; cid < rowset_schema->num_columns(); cid++) {
1303
0
        MutableColumnPtr& new_col = full_mutable_columns[cid];
1304
0
        const IColumn& cur_col = *update_block.get_by_position(cid).column;
1305
0
        const auto& rs_column = rowset_schema->column(cid);
1306
0
        auto col_uid = rs_column.unique_id();
1307
0
        for (auto idx = 0; idx < update_rows; ++idx) {
1308
0
            if (cid < rowset_schema->num_key_columns()) {
1309
0
                new_col->insert_from(cur_col, read_index_update[idx]);
1310
0
            } else {
1311
0
                const IColumn& default_value_col =
1312
0
                        *default_value_block.get_by_position(cid - rowset_schema->num_key_columns())
1313
0
                                 .column;
1314
0
                const IColumn& old_value_col =
1315
0
                        *old_block.get_by_position(cid - rowset_schema->num_key_columns()).column;
1316
0
                if (rids_be_overwritten.contains(idx)) {
1317
0
                    new_col->insert_from(old_value_col, read_index_old[idx]);
1318
0
                } else {
1319
0
                    fill_cell_for_flexible_partial_update(
1320
0
                            read_index_old, read_index_update, rowset_schema, partial_update_info,
1321
0
                            rs_column, idx, new_col, default_value_col, old_value_col, cur_col,
1322
0
                            skip_bitmaps->at(idx).contains(col_uid),
1323
0
                            rowset_schema->has_sequence_col()
1324
0
                                    ? !skip_bitmaps->at(idx).contains(seq_col_unique_id)
1325
0
                                    : false,
1326
0
                            old_block_delete_signs);
1327
0
                }
1328
0
            }
1329
0
        }
1330
0
        DCHECK_EQ(full_mutable_columns[cid]->size(), update_rows);
1331
0
    }
1332
1333
0
    full_mutable_columns_guard.restore();
1334
0
    VLOG_DEBUG << "full block when publish: " << output_block->dump_data();
1335
0
    return Status::OK();
1336
0
}
1337
1338
Status BaseTablet::commit_phase_update_delete_bitmap(
1339
        const BaseTabletSPtr& tablet, const RowsetSharedPtr& rowset,
1340
        RowsetIdUnorderedSet& pre_rowset_ids, DeleteBitmapPtr delete_bitmap,
1341
        const std::vector<segment_v2::SegmentSharedPtr>& segments, int64_t txn_id,
1342
36.7k
        CalcDeleteBitmapToken* token, RowsetWriter* rowset_writer) {
1343
36.7k
    DBUG_EXECUTE_IF("BaseTablet::commit_phase_update_delete_bitmap.enable_spin_wait", {
1344
36.7k
        auto tok = dp->param<std::string>("token", "invalid_token");
1345
36.7k
        while (DebugPoints::instance()->is_enable(
1346
36.7k
                "BaseTablet::commit_phase_update_delete_bitmap.block")) {
1347
36.7k
            auto block_dp = DebugPoints::instance()->get_debug_point(
1348
36.7k
                    "BaseTablet::commit_phase_update_delete_bitmap.block");
1349
36.7k
            if (block_dp) {
1350
36.7k
                auto pass_token = block_dp->param<std::string>("pass_token", "");
1351
36.7k
                if (pass_token == tok) {
1352
36.7k
                    break;
1353
36.7k
                }
1354
36.7k
            }
1355
36.7k
            std::this_thread::sleep_for(std::chrono::milliseconds(50));
1356
36.7k
        }
1357
36.7k
    });
1358
36.7k
    SCOPED_BVAR_LATENCY(g_tablet_commit_phase_update_delete_bitmap_latency);
1359
36.7k
    RowsetIdUnorderedSet cur_rowset_ids;
1360
36.7k
    RowsetIdUnorderedSet rowset_ids_to_add;
1361
36.7k
    RowsetIdUnorderedSet rowset_ids_to_del;
1362
36.7k
    int64_t cur_version;
1363
1364
36.7k
    std::vector<RowsetSharedPtr> specified_rowsets;
1365
36.7k
    {
1366
        // to prevent seeing intermediate state of a tablet
1367
36.7k
        std::unique_lock<bthread::Mutex> sync_lock;
1368
36.7k
        if (config::is_cloud_mode()) {
1369
19.8k
            sync_lock = std::unique_lock<bthread::Mutex>(
1370
19.8k
                    std::static_pointer_cast<CloudTablet>(tablet)->get_sync_meta_lock());
1371
19.8k
        }
1372
36.7k
        std::shared_lock meta_rlock(tablet->_meta_lock);
1373
36.7k
        if (tablet->tablet_state() == TABLET_NOTREADY) {
1374
            // tablet is under alter process. The delete bitmap will be calculated after conversion.
1375
27
            LOG(INFO) << "tablet is under alter process, delete bitmap will be calculated later, "
1376
27
                         "tablet_id: "
1377
27
                      << tablet->tablet_id() << " txn_id: " << txn_id;
1378
27
            return Status::OK();
1379
27
        }
1380
36.7k
        cur_version = tablet->max_version_unlocked();
1381
36.7k
        RETURN_IF_ERROR(tablet->get_all_rs_id_unlocked(cur_version, &cur_rowset_ids));
1382
36.7k
        _rowset_ids_difference(cur_rowset_ids, pre_rowset_ids, &rowset_ids_to_add,
1383
36.7k
                               &rowset_ids_to_del);
1384
36.7k
        specified_rowsets = tablet->get_rowset_by_ids(&rowset_ids_to_add);
1385
36.7k
    }
1386
11.6k
    for (const auto& to_del : rowset_ids_to_del) {
1387
11.6k
        delete_bitmap->remove({to_del, 0, 0}, {to_del, UINT32_MAX, INT64_MAX});
1388
11.6k
    }
1389
1390
36.7k
    RETURN_IF_ERROR(calc_delete_bitmap(tablet, rowset, segments, specified_rowsets, delete_bitmap,
1391
36.7k
                                       cur_version, token, rowset_writer));
1392
36.7k
    size_t total_rows = std::accumulate(
1393
36.7k
            segments.begin(), segments.end(), 0,
1394
36.7k
            [](size_t sum, const segment_v2::SegmentSharedPtr& s) { return sum += s->num_rows(); });
1395
36.7k
    LOG(INFO) << "[Before Commit] construct delete bitmap tablet: " << tablet->tablet_id()
1396
36.7k
              << ", rowset_ids to add: " << rowset_ids_to_add.size()
1397
36.7k
              << ", rowset_ids to del: " << rowset_ids_to_del.size()
1398
36.7k
              << ", cur max_version: " << cur_version << ", transaction_id: " << txn_id
1399
36.7k
              << ", total rows: " << total_rows;
1400
36.7k
    pre_rowset_ids = cur_rowset_ids;
1401
36.7k
    return Status::OK();
1402
36.7k
}
1403
1404
void BaseTablet::add_sentinel_mark_to_delete_bitmap(DeleteBitmap* delete_bitmap,
1405
39.7k
                                                    const RowsetIdUnorderedSet& rowsetids) {
1406
301k
    for (const auto& rowsetid : rowsetids) {
1407
301k
        delete_bitmap->add(
1408
301k
                {rowsetid, DeleteBitmap::INVALID_SEGMENT_ID, DeleteBitmap::TEMP_VERSION_COMMON},
1409
301k
                DeleteBitmap::ROWSET_SENTINEL_MARK);
1410
301k
    }
1411
39.7k
}
1412
1413
void BaseTablet::_rowset_ids_difference(const RowsetIdUnorderedSet& cur,
1414
                                        const RowsetIdUnorderedSet& pre,
1415
                                        RowsetIdUnorderedSet* to_add,
1416
91.2k
                                        RowsetIdUnorderedSet* to_del) {
1417
657k
    for (const auto& id : cur) {
1418
657k
        if (pre.find(id) == pre.end()) {
1419
14.7k
            to_add->insert(id);
1420
14.7k
        }
1421
657k
    }
1422
657k
    for (const auto& id : pre) {
1423
657k
        if (cur.find(id) == cur.end()) {
1424
15.1k
            to_del->insert(id);
1425
15.1k
        }
1426
657k
    }
1427
91.2k
}
1428
1429
Status BaseTablet::check_delete_bitmap_correctness(DeleteBitmapPtr delete_bitmap,
1430
                                                   int64_t max_version, int64_t txn_id,
1431
                                                   const RowsetIdUnorderedSet& rowset_ids,
1432
76.3k
                                                   std::vector<RowsetSharedPtr>* rowsets) {
1433
76.3k
    RowsetIdUnorderedSet missing_ids;
1434
581k
    for (const auto& rowsetid : rowset_ids) {
1435
581k
        if (!delete_bitmap->delete_bitmap.contains({rowsetid, DeleteBitmap::INVALID_SEGMENT_ID,
1436
581k
                                                    DeleteBitmap::TEMP_VERSION_COMMON})) {
1437
0
            missing_ids.insert(rowsetid);
1438
0
        }
1439
581k
    }
1440
1441
76.3k
    if (!missing_ids.empty()) {
1442
0
        LOG(WARNING) << "[txn_id:" << txn_id << "][tablet_id:" << tablet_id()
1443
0
                     << "][max_version: " << max_version
1444
0
                     << "] check delete bitmap correctness failed!";
1445
0
        rapidjson::Document root;
1446
0
        root.SetObject();
1447
0
        rapidjson::Document required_rowsets_arr;
1448
0
        required_rowsets_arr.SetArray();
1449
0
        rapidjson::Document missing_rowsets_arr;
1450
0
        missing_rowsets_arr.SetArray();
1451
1452
0
        if (rowsets != nullptr) {
1453
0
            for (const auto& rowset : *rowsets) {
1454
0
                rapidjson::Value value;
1455
0
                std::string version_str = rowset->get_rowset_info_str();
1456
0
                value.SetString(version_str.c_str(),
1457
0
                                cast_set<rapidjson::SizeType>(version_str.length()),
1458
0
                                required_rowsets_arr.GetAllocator());
1459
0
                required_rowsets_arr.PushBack(value, required_rowsets_arr.GetAllocator());
1460
0
            }
1461
0
        } else {
1462
0
            std::vector<RowsetSharedPtr> tablet_rowsets;
1463
0
            {
1464
0
                std::shared_lock meta_rlock(_meta_lock);
1465
0
                tablet_rowsets = get_rowset_by_ids(&rowset_ids);
1466
0
            }
1467
0
            for (const auto& rowset : tablet_rowsets) {
1468
0
                rapidjson::Value value;
1469
0
                std::string version_str = rowset->get_rowset_info_str();
1470
0
                value.SetString(version_str.c_str(),
1471
0
                                cast_set<rapidjson::SizeType>(version_str.length()),
1472
0
                                required_rowsets_arr.GetAllocator());
1473
0
                required_rowsets_arr.PushBack(value, required_rowsets_arr.GetAllocator());
1474
0
            }
1475
0
        }
1476
0
        for (const auto& missing_rowset_id : missing_ids) {
1477
0
            rapidjson::Value miss_value;
1478
0
            std::string rowset_id_str = missing_rowset_id.to_string();
1479
0
            miss_value.SetString(rowset_id_str.c_str(),
1480
0
                                 cast_set<rapidjson::SizeType>(rowset_id_str.length()),
1481
0
                                 missing_rowsets_arr.GetAllocator());
1482
0
            missing_rowsets_arr.PushBack(miss_value, missing_rowsets_arr.GetAllocator());
1483
0
        }
1484
1485
0
        root.AddMember("required_rowsets", required_rowsets_arr, root.GetAllocator());
1486
0
        root.AddMember("missing_rowsets", missing_rowsets_arr, root.GetAllocator());
1487
0
        rapidjson::StringBuffer strbuf;
1488
0
        rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(strbuf);
1489
0
        root.Accept(writer);
1490
0
        std::string rowset_status_string = std::string(strbuf.GetString());
1491
0
        LOG_EVERY_SECOND(WARNING) << rowset_status_string;
1492
        // let it crash if correctness check failed in Debug mode
1493
0
        DCHECK(false) << "delete bitmap correctness check failed in publish phase!";
1494
0
        return Status::InternalError("check delete bitmap failed!");
1495
0
    }
1496
76.3k
    return Status::OK();
1497
76.3k
}
1498
1499
Status BaseTablet::update_delete_bitmap(const BaseTabletSPtr& self, TabletTxnInfo* txn_info,
1500
                                        int64_t txn_id, int64_t txn_expiration,
1501
54.7k
                                        DeleteBitmapPtr tablet_delete_bitmap) {
1502
54.7k
    SCOPED_BVAR_LATENCY(g_tablet_update_delete_bitmap_latency);
1503
54.7k
    RowsetIdUnorderedSet cur_rowset_ids;
1504
54.7k
    RowsetIdUnorderedSet rowset_ids_to_add;
1505
54.7k
    RowsetIdUnorderedSet rowset_ids_to_del;
1506
54.7k
    RowsetSharedPtr rowset = txn_info->rowset;
1507
54.7k
    RowsetSharedPtr row_binlog_rowset;
1508
54.7k
    bool build_row_binlog = false;
1509
54.7k
    int64_t cur_version = rowset->start_version();
1510
54.7k
    std::unique_ptr<RowsetWriter> transient_rs_writer;
1511
54.7k
    DeleteBitmapPtr delete_bitmap = txn_info->delete_bitmap;
1512
54.7k
    bool is_partial_update =
1513
54.8k
            txn_info->partial_update_info && txn_info->partial_update_info->is_partial_update();
1514
54.7k
    const auto& binlog_rs = txn_info->attach_row_binlog.rowset;
1515
54.7k
    if (binlog_rs != nullptr && binlog_rs->rowset_meta() != nullptr &&
1516
54.7k
        binlog_rs->rowset_meta()->is_row_binlog()) {
1517
0
        DCHECK(txn_info->attach_row_binlog.tablet != nullptr);
1518
0
        row_binlog_rowset = binlog_rs;
1519
0
        const auto& binlog_tablet_meta = txn_info->attach_row_binlog.tablet->tablet_meta();
1520
0
        build_row_binlog =
1521
0
                is_partial_update || binlog_tablet_meta->binlog_config().need_historical_value();
1522
0
    }
1523
1524
    // rewrite conflict only when partial update or need before
1525
54.7k
    if (is_partial_update || build_row_binlog) {
1526
1.90k
        if (txn_info->partial_update_info == nullptr) {
1527
0
            txn_info->partial_update_info = std::make_shared<PartialUpdateInfo>();
1528
0
        }
1529
1.90k
        if (txn_info->partial_update_info->partial_update_mode == UniqueKeyUpdateModePB::UPSERT) {
1530
0
            txn_info->partial_update_info->partial_update_input_columns.clear();
1531
0
            txn_info->partial_update_info->missing_cids.clear();
1532
0
            txn_info->partial_update_info->default_values.clear();
1533
0
            auto& update_cids = txn_info->partial_update_info->update_cids;
1534
0
            update_cids.resize(rowset->tablet_schema()->num_columns());
1535
0
            std::iota(update_cids.begin(), update_cids.end(), 0);
1536
0
        }
1537
1538
1.90k
        DCHECK(txn_info->partial_update_info != nullptr);
1539
1540
1.90k
        transient_rs_writer = DORIS_TRY(self->create_transient_rowset_writer(
1541
1.90k
                *rowset, txn_info->partial_update_info, txn_expiration));
1542
1.90k
        DBUG_EXECUTE_IF("BaseTablet::update_delete_bitmap.after.create_transient_rs_writer",
1543
1.90k
                        DBUG_BLOCK);
1544
        // Partial update or upsert rewrite might generate new segments when there is conflicts while publish, and mark
1545
        // the same key in original segments as delete.
1546
        // When the new segment flush fails or the rowset build fails, the deletion marker for the
1547
        // duplicate key of the original segment should not remain in `txn_info->delete_bitmap`,
1548
        // so we need to make a copy of `txn_info->delete_bitmap` and make changes on it.
1549
1.90k
        delete_bitmap = std::make_shared<DeleteBitmap>(*(txn_info->delete_bitmap));
1550
1.90k
    }
1551
1552
54.7k
    OlapStopWatch watch;
1553
54.7k
    std::vector<segment_v2::SegmentSharedPtr> segments;
1554
54.7k
    RETURN_IF_ERROR(std::dynamic_pointer_cast<BetaRowset>(rowset)->load_segments(&segments));
1555
54.7k
    auto t1 = watch.get_elapse_time_us();
1556
1557
54.7k
    int64_t next_visible_version = txn_info->is_txn_load ? txn_info->next_visible_version
1558
54.7k
                                                         : txn_info->rowset->start_version();
1559
54.7k
    {
1560
54.7k
        std::shared_lock meta_rlock(self->_meta_lock);
1561
        // tablet is under alter process. The delete bitmap will be calculated after conversion.
1562
54.7k
        if (self->tablet_state() == TABLET_NOTREADY) {
1563
4
            LOG(INFO) << "tablet is under alter process, update delete bitmap later, tablet_id="
1564
4
                      << self->tablet_id();
1565
4
            return Status::OK();
1566
4
        }
1567
54.7k
        RETURN_IF_ERROR(self->get_all_rs_id_unlocked(next_visible_version - 1, &cur_rowset_ids));
1568
54.7k
    }
1569
54.7k
    auto t2 = watch.get_elapse_time_us();
1570
1571
54.7k
    _rowset_ids_difference(cur_rowset_ids, txn_info->rowset_ids, &rowset_ids_to_add,
1572
54.7k
                           &rowset_ids_to_del);
1573
54.7k
    for (const auto& to_del : rowset_ids_to_del) {
1574
3.46k
        delete_bitmap->remove({to_del, 0, 0}, {to_del, UINT32_MAX, INT64_MAX});
1575
3.46k
    }
1576
1577
54.7k
    std::vector<RowsetSharedPtr> specified_rowsets;
1578
54.7k
    {
1579
54.7k
        std::shared_lock meta_rlock(self->_meta_lock);
1580
54.7k
        specified_rowsets = self->get_rowset_by_ids(&rowset_ids_to_add);
1581
54.7k
    }
1582
54.7k
    if (txn_info->is_txn_load) {
1583
110
        for (auto invisible_rowset : txn_info->invisible_rowsets) {
1584
37
            specified_rowsets.emplace_back(invisible_rowset);
1585
37
        }
1586
110
        std::sort(specified_rowsets.begin(), specified_rowsets.end(),
1587
509
                  [](RowsetSharedPtr& lhs, RowsetSharedPtr& rhs) {
1588
509
                      return lhs->end_version() > rhs->end_version();
1589
509
                  });
1590
110
    }
1591
54.7k
    auto t3 = watch.get_elapse_time_us();
1592
1593
    // If a rowset is produced by compaction before the commit phase of the partial update load
1594
    // and is not included in txn_info->rowset_ids, we can skip the alignment process of that rowset
1595
    // because data remains the same before and after compaction. But we still need to calculate the
1596
    // the delete bitmap for that rowset.
1597
54.7k
    std::vector<RowsetSharedPtr> rowsets_skip_alignment;
1598
54.7k
    if (is_partial_update) {
1599
1.93k
        int64_t max_version_in_flush_phase =
1600
1.93k
                txn_info->partial_update_info->max_version_in_flush_phase;
1601
1.93k
        DCHECK(max_version_in_flush_phase != -1);
1602
1.93k
        std::vector<RowsetSharedPtr> remained_rowsets;
1603
1.93k
        for (const auto& specified_rowset : specified_rowsets) {
1604
243
            if (specified_rowset->end_version() <= max_version_in_flush_phase &&
1605
243
                specified_rowset->produced_by_compaction()) {
1606
28
                rowsets_skip_alignment.emplace_back(specified_rowset);
1607
215
            } else {
1608
215
                remained_rowsets.emplace_back(specified_rowset);
1609
215
            }
1610
243
        }
1611
1.93k
        if (!rowsets_skip_alignment.empty()) {
1612
29
            specified_rowsets = std::move(remained_rowsets);
1613
29
        }
1614
1.93k
    }
1615
1616
54.7k
    DBUG_EXECUTE_IF("BaseTablet::update_delete_bitmap.enable_spin_wait", {
1617
54.7k
        auto token = dp->param<std::string>("token", "invalid_token");
1618
54.7k
        while (DebugPoints::instance()->is_enable("BaseTablet::update_delete_bitmap.block")) {
1619
54.7k
            auto block_dp = DebugPoints::instance()->get_debug_point(
1620
54.7k
                    "BaseTablet::update_delete_bitmap.block");
1621
54.7k
            if (block_dp) {
1622
54.7k
                auto wait_token = block_dp->param<std::string>("wait_token", "");
1623
54.7k
                LOG(INFO) << "BaseTablet::update_delete_bitmap.enable_spin_wait, wait_token: "
1624
54.7k
                          << wait_token << ", token: " << token;
1625
54.7k
                if (wait_token != token) {
1626
54.7k
                    break;
1627
54.7k
                }
1628
54.7k
            }
1629
54.7k
            std::this_thread::sleep_for(std::chrono::milliseconds(50));
1630
54.7k
        }
1631
54.7k
    });
1632
1633
54.7k
    if (!rowsets_skip_alignment.empty()) {
1634
27
        auto token = self->calc_delete_bitmap_executor()->create_token();
1635
        // set rowset_writer to nullptr to skip the alignment process
1636
27
        RETURN_IF_ERROR(calc_delete_bitmap(self, rowset, segments, rowsets_skip_alignment,
1637
27
                                           delete_bitmap, cur_version - 1, token.get(), nullptr,
1638
27
                                           tablet_delete_bitmap));
1639
27
        RETURN_IF_ERROR(token->wait());
1640
27
    }
1641
1642
    // Publish-phase partial update or upsert rewrite may generate transient segments. If row binlog is enabled for
1643
    // this txn (row binlog rowset attached), we need to build row binlog segments together with
1644
    // transient data segments:
1645
    // 1) create a transient row binlog writer that appends to the same version row binlog rowset
1646
    // 2) pre-allocate per-row LSNs for each transient segment and register them in binlog options
1647
    // 3) wrap both writers into a GroupRowsetWriter so calc_delete_bitmap writes to both.
1648
54.7k
    if (build_row_binlog) {
1649
0
        DCHECK(transient_rs_writer != nullptr);
1650
1651
        // Create transient row binlog writer for publish-phase segment appending.
1652
0
        auto transient_row_binlog_writer =
1653
0
                DORIS_TRY(txn_info->attach_row_binlog.tablet->create_transient_rowset_writer(
1654
0
                        *row_binlog_rowset, txn_info->partial_update_info, txn_expiration));
1655
1656
        // Prepare source MOW context for historical row retrieval in binlog writer.
1657
0
        auto& data_ctx = const_cast<RowsetWriterContext&>(transient_rs_writer->context());
1658
0
        data_ctx.mow_context = std::make_shared<MowContext>(
1659
0
                cur_version - 1, txn_id, std::make_shared<RowsetIdUnorderedSet>(),
1660
0
                specified_rowsets, nullptr);
1661
1662
0
        auto& binlog_ctx = const_cast<RowsetWriterContext&>(transient_row_binlog_writer->context());
1663
0
        auto& cfg = binlog_ctx.write_binlog_opt().write_binlog_config();
1664
0
        cfg.source.tablet_schema = data_ctx.tablet_schema;
1665
0
        cfg.source.partial_update_info = data_ctx.partial_update_info;
1666
0
        cfg.source.mow_context = data_ctx.mow_context;
1667
0
        cfg.source.is_transient_rowset_writer = data_ctx.is_transient_rowset_writer;
1668
0
        cfg.source.source_write_type = data_ctx.write_type;
1669
0
        cfg.source.row_binlog_rowset = row_binlog_rowset;
1670
0
        cfg.source.base_tablet = self;
1671
1672
        // Wrap two transient writers into a group writer for dual flush/build.
1673
0
        RowsetWriterSharedPtr data_writer_sp(std::move(transient_rs_writer));
1674
0
        RowsetWriterSharedPtr row_binlog_writer_sp(std::move(transient_row_binlog_writer));
1675
0
        std::unique_ptr<GroupRowsetWriter> group_writer;
1676
0
        RETURN_IF_ERROR(RowsetFactory::create_empty_group_rowset_writer(&group_writer));
1677
0
        group_writer->set_data_writer(data_writer_sp);
1678
0
        group_writer->set_row_binlog_writer(row_binlog_writer_sp);
1679
0
        transient_rs_writer = std::move(group_writer);
1680
0
    }
1681
1682
    // When there is only one segment, it will be calculated in the current thread.
1683
    // Otherwise, it will be submitted to the thread pool for calculation.
1684
54.7k
    if (segments.size() <= 1) {
1685
54.3k
        RETURN_IF_ERROR(calc_delete_bitmap(self, rowset, segments, specified_rowsets, delete_bitmap,
1686
54.3k
                                           cur_version - 1, nullptr, transient_rs_writer.get(),
1687
54.3k
                                           tablet_delete_bitmap));
1688
1689
54.3k
    } else {
1690
377
        auto token = self->calc_delete_bitmap_executor()->create_token();
1691
377
        RETURN_IF_ERROR(calc_delete_bitmap(self, rowset, segments, specified_rowsets, delete_bitmap,
1692
377
                                           cur_version - 1, token.get(), transient_rs_writer.get(),
1693
377
                                           tablet_delete_bitmap));
1694
377
        RETURN_IF_ERROR(token->wait());
1695
377
    }
1696
1697
54.7k
    std::stringstream ss;
1698
54.7k
    ss << "cost(us): (load segments: " << t1 << ", get all rsid: " << t2 - t1
1699
54.7k
       << ", get rowsets: " << t3 - t2
1700
54.7k
       << ", calc delete bitmap: " << watch.get_elapse_time_us() - t3 << ")";
1701
1702
54.7k
    if (config::enable_merge_on_write_correctness_check && rowset->num_rows() != 0) {
1703
        // only do correctness check if the rowset has at least one row written
1704
        // check if all the rowset has ROWSET_SENTINEL_MARK
1705
38.0k
        auto st = self->check_delete_bitmap_correctness(delete_bitmap, cur_version - 1, -1,
1706
38.0k
                                                        cur_rowset_ids, &specified_rowsets);
1707
38.0k
        if (!st.ok()) {
1708
0
            LOG(WARNING) << fmt::format("delete bitmap correctness check failed in publish phase!");
1709
0
        }
1710
38.0k
    }
1711
1712
54.7k
    if (transient_rs_writer) {
1713
1.90k
        auto t4 = watch.get_elapse_time_us();
1714
1.90k
        DBUG_EXECUTE_IF("Tablet.update_delete_bitmap.partial_update_write_rowset_fail", {
1715
1.90k
            if (rand() % 100 < (100 * dp->param("percent", 0.5))) {
1716
1.90k
                LOG_WARNING("Tablet.update_delete_bitmap.partial_update_write_rowset random failed")
1717
1.90k
                        .tag("txn_id", txn_id);
1718
1.90k
                return Status::InternalError(
1719
1.90k
                        "debug update_delete_bitmap partial update write rowset random failed");
1720
1.90k
            }
1721
1.90k
        });
1722
        // build rowset writer and merge transient rowset
1723
1.90k
        RETURN_IF_ERROR(transient_rs_writer->flush());
1724
1.90k
        RowsetSharedPtr transient_rowset;
1725
1.90k
        RowsetSharedPtr transient_row_binlog;
1726
1.90k
        if (build_row_binlog) {
1727
0
            auto* group_rowset_writer = typeid_cast<GroupRowsetWriter*>(transient_rs_writer.get());
1728
0
            DCHECK(group_rowset_writer != nullptr);
1729
0
            std::vector<RowsetSharedPtr> waited_build_rowsets;
1730
0
            RETURN_IF_ERROR(group_rowset_writer->build_rowsets(waited_build_rowsets));
1731
0
            transient_rowset = waited_build_rowsets.at(0);
1732
0
            transient_row_binlog = waited_build_rowsets.at(1);
1733
1.90k
        } else {
1734
1.90k
            RETURN_IF_ERROR(transient_rs_writer->build(transient_rowset));
1735
1.90k
        }
1736
1.90k
        auto old_segments = rowset->num_segments();
1737
1.90k
        rowset->merge_rowset_meta(*transient_rowset->rowset_meta());
1738
1.90k
        auto new_segments = rowset->num_segments();
1739
1.90k
        ss << ", " << txn_info->partial_update_info->partial_update_mode_str()
1740
1.90k
           << " flush rowset (old segment num: " << old_segments
1741
1.90k
           << ", new segment num: " << new_segments << ")"
1742
1.90k
           << ", cost:" << watch.get_elapse_time_us() - t4 << "(us)";
1743
1744
1.90k
        if (build_row_binlog) {
1745
0
            DCHECK(row_binlog_rowset != nullptr);
1746
0
            old_segments = row_binlog_rowset->num_segments();
1747
0
            row_binlog_rowset->merge_rowset_meta(*transient_row_binlog->rowset_meta());
1748
0
            new_segments = row_binlog_rowset->num_segments();
1749
0
            ss << ", " << txn_info->partial_update_info->partial_update_mode_str()
1750
0
               << " flush binlog<row> (old segment num: " << old_segments
1751
0
               << ", new segment num: " << new_segments << ")";
1752
1753
0
            SegmentLoader::instance()->erase_segments(row_binlog_rowset->rowset_id(),
1754
0
                                                      row_binlog_rowset->num_segments());
1755
0
        }
1756
1757
        // update the shared_ptr to new bitmap, which is consistent with current rowset.
1758
1.90k
        txn_info->delete_bitmap = delete_bitmap;
1759
        // erase segment cache cause we will add a segment to rowset
1760
1.90k
        SegmentLoader::instance()->erase_segments(rowset->rowset_id(), rowset->num_segments());
1761
1.90k
    }
1762
1763
54.7k
    size_t total_rows = std::accumulate(
1764
54.7k
            segments.begin(), segments.end(), 0,
1765
54.7k
            [](size_t sum, const segment_v2::SegmentSharedPtr& s) { return sum += s->num_rows(); });
1766
54.7k
    auto t5 = watch.get_elapse_time_us();
1767
54.7k
    int64_t lock_id = txn_info->is_txn_load ? txn_info->lock_id : -1;
1768
54.7k
    RETURN_IF_ERROR(self->save_delete_bitmap(txn_info, txn_id, delete_bitmap,
1769
54.7k
                                             transient_rs_writer.get(), cur_rowset_ids, lock_id,
1770
54.7k
                                             next_visible_version));
1771
1772
    // defensive check, check that the delete bitmap cache we wrote is correct
1773
54.7k
    RETURN_IF_ERROR(self->check_delete_bitmap_cache(txn_id, delete_bitmap.get()));
1774
1775
54.7k
    LOG(INFO) << "[Publish] construct delete bitmap tablet: " << self->tablet_id()
1776
54.7k
              << ", rowset_ids to add: "
1777
54.7k
              << (specified_rowsets.size() + rowsets_skip_alignment.size())
1778
54.7k
              << ", rowset_ids to del: " << rowset_ids_to_del.size()
1779
54.7k
              << ", cur version: " << cur_version << ", transaction_id: " << txn_id << ","
1780
54.7k
              << ss.str() << " , total rows: " << total_rows
1781
54.7k
              << ", update delete_bitmap cost: " << watch.get_elapse_time_us() - t5 << "(us)";
1782
54.7k
    return Status::OK();
1783
54.7k
}
1784
1785
void BaseTablet::calc_compaction_output_rowset_delete_bitmap(
1786
        const std::vector<RowsetSharedPtr>& input_rowsets, const RowIdConversion& rowid_conversion,
1787
        uint64_t start_version, uint64_t end_version, std::set<RowLocation>* missed_rows,
1788
        std::map<RowsetSharedPtr, std::list<std::pair<RowLocation, RowLocation>>>* location_map,
1789
12.7k
        const DeleteBitmap& input_delete_bitmap, DeleteBitmap* output_rowset_delete_bitmap) {
1790
12.7k
    RowLocation src;
1791
12.7k
    RowLocation dst;
1792
126k
    for (auto& rowset : input_rowsets) {
1793
126k
        src.rowset_id = rowset->rowset_id();
1794
191k
        for (uint32_t seg_id = 0; seg_id < rowset->num_segments(); ++seg_id) {
1795
64.8k
            src.segment_id = seg_id;
1796
64.8k
            DeleteBitmap subset_map(tablet_id());
1797
64.8k
            input_delete_bitmap.subset({rowset->rowset_id(), seg_id, start_version},
1798
64.8k
                                       {rowset->rowset_id(), seg_id, end_version}, &subset_map);
1799
            // traverse all versions and convert rowid
1800
64.8k
            for (auto iter = subset_map.delete_bitmap.begin();
1801
72.0k
                 iter != subset_map.delete_bitmap.end(); ++iter) {
1802
7.23k
                auto cur_version = std::get<2>(iter->first);
1803
2.79M
                for (auto index = iter->second.begin(); index != iter->second.end(); ++index) {
1804
2.79M
                    src.row_id = *index;
1805
2.79M
                    if (rowid_conversion.get(src, &dst) != 0) {
1806
2.19M
                        VLOG_CRITICAL << "Can't find rowid, may be deleted by the delete_handler, "
1807
0
                                      << " src loaction: |" << src.rowset_id << "|"
1808
0
                                      << src.segment_id << "|" << src.row_id
1809
0
                                      << " version: " << cur_version;
1810
2.19M
                        if (missed_rows) {
1811
1.79k
                            missed_rows->insert(src);
1812
1.79k
                        }
1813
2.19M
                        continue;
1814
2.19M
                    }
1815
600k
                    VLOG_DEBUG << "calc_compaction_output_rowset_delete_bitmap dst location: |"
1816
1
                               << dst.rowset_id << "|" << dst.segment_id << "|" << dst.row_id
1817
1
                               << " src location: |" << src.rowset_id << "|" << src.segment_id
1818
1
                               << "|" << src.row_id << " start version: " << start_version
1819
1
                               << "end version" << end_version;
1820
600k
                    if (location_map) {
1821
0
                        (*location_map)[rowset].emplace_back(src, dst);
1822
0
                    }
1823
600k
                    output_rowset_delete_bitmap->add({dst.rowset_id, dst.segment_id, cur_version},
1824
600k
                                                     dst.row_id);
1825
600k
                }
1826
7.23k
            }
1827
64.8k
        }
1828
126k
    }
1829
12.7k
}
1830
1831
Status BaseTablet::check_rowid_conversion(
1832
        RowsetSharedPtr dst_rowset,
1833
        const std::map<RowsetSharedPtr, std::list<std::pair<RowLocation, RowLocation>>>&
1834
0
                location_map) {
1835
0
    if (location_map.empty()) {
1836
0
        VLOG_DEBUG << "check_rowid_conversion, location_map is empty";
1837
0
        return Status::OK();
1838
0
    }
1839
0
    std::vector<segment_v2::SegmentSharedPtr> dst_segments;
1840
1841
0
    RETURN_IF_ERROR(
1842
0
            std::dynamic_pointer_cast<BetaRowset>(dst_rowset)->load_segments(&dst_segments));
1843
0
    std::unordered_map<RowsetId, std::vector<segment_v2::SegmentSharedPtr>> input_rowsets_segment;
1844
1845
0
    VLOG_DEBUG << "check_rowid_conversion, dst_segments size: " << dst_segments.size();
1846
0
    for (auto [src_rowset, locations] : location_map) {
1847
0
        std::vector<segment_v2::SegmentSharedPtr>& segments =
1848
0
                input_rowsets_segment[src_rowset->rowset_id()];
1849
0
        if (segments.empty()) {
1850
0
            RETURN_IF_ERROR(
1851
0
                    std::dynamic_pointer_cast<BetaRowset>(src_rowset)->load_segments(&segments));
1852
0
        }
1853
0
        for (auto& [src, dst] : locations) {
1854
0
            std::string src_key;
1855
0
            std::string dst_key;
1856
0
            Status s = segments[src.segment_id]->read_key_by_rowid(src.row_id, &src_key);
1857
0
            if (UNLIKELY(s.is<NOT_IMPLEMENTED_ERROR>())) {
1858
0
                LOG(INFO) << "primary key index of old version does not "
1859
0
                             "support reading key by rowid";
1860
0
                break;
1861
0
            }
1862
0
            if (UNLIKELY(!s)) {
1863
0
                LOG(WARNING) << "failed to get src key: |" << src.rowset_id << "|" << src.segment_id
1864
0
                             << "|" << src.row_id << " status: " << s;
1865
0
                DCHECK(false);
1866
0
                return s;
1867
0
            }
1868
1869
0
            s = dst_segments[dst.segment_id]->read_key_by_rowid(dst.row_id, &dst_key);
1870
0
            if (UNLIKELY(!s)) {
1871
0
                LOG(WARNING) << "failed to get dst key: |" << dst.rowset_id << "|" << dst.segment_id
1872
0
                             << "|" << dst.row_id << " status: " << s;
1873
0
                DCHECK(false);
1874
0
                return s;
1875
0
            }
1876
1877
0
            VLOG_DEBUG << "check_rowid_conversion, src: |" << src.rowset_id << "|" << src.segment_id
1878
0
                       << "|" << src.row_id << "|" << src_key << " dst: |" << dst.rowset_id << "|"
1879
0
                       << dst.segment_id << "|" << dst.row_id << "|" << dst_key;
1880
0
            if (UNLIKELY(src_key.compare(dst_key) != 0)) {
1881
0
                LOG(WARNING) << "failed to check key, src key: |" << src.rowset_id << "|"
1882
0
                             << src.segment_id << "|" << src.row_id << "|" << src_key
1883
0
                             << " dst key: |" << dst.rowset_id << "|" << dst.segment_id << "|"
1884
0
                             << dst.row_id << "|" << dst_key;
1885
0
                DCHECK(false);
1886
0
                return Status::InternalError("failed to check rowid conversion");
1887
0
            }
1888
0
        }
1889
0
    }
1890
0
    return Status::OK();
1891
0
}
1892
1893
// The caller should hold _rowset_update_lock and _meta_lock lock.
1894
Status BaseTablet::update_delete_bitmap_without_lock(
1895
        const BaseTabletSPtr& self, const RowsetSharedPtr& rowset,
1896
26
        const std::vector<RowsetSharedPtr>* specified_base_rowsets) {
1897
26
    DBUG_EXECUTE_IF("BaseTablet.update_delete_bitmap_without_lock.random_failed", {
1898
26
        auto rnd = rand() % 100;
1899
26
        auto percent = dp->param("percent", 0.1);
1900
26
        if (rnd < (100 * percent)) {
1901
26
            LOG(WARNING) << "BaseTablet.update_delete_bitmap_without_lock.random_failed";
1902
26
            return Status::InternalError(
1903
26
                    "debug tablet update delete bitmap without lock random failed");
1904
26
        } else {
1905
26
            LOG(INFO) << "BaseTablet.update_delete_bitmap_without_lock.random_failed not "
1906
26
                         "triggered"
1907
26
                      << ", rnd:" << rnd << ", percent: " << percent;
1908
26
        }
1909
26
    });
1910
26
    int64_t cur_version = rowset->start_version();
1911
26
    std::vector<segment_v2::SegmentSharedPtr> segments;
1912
26
    RETURN_IF_ERROR(std::dynamic_pointer_cast<BetaRowset>(rowset)->load_segments(&segments));
1913
1914
    // If this rowset does not have a segment, there is no need for an update.
1915
26
    if (segments.empty()) {
1916
7
        LOG(INFO) << "[Schema Change or Clone] skip to construct delete bitmap tablet: "
1917
7
                  << self->tablet_id() << " cur max_version: " << cur_version;
1918
7
        return Status::OK();
1919
7
    }
1920
1921
    // calculate delete bitmap between segments if necessary.
1922
19
    DeleteBitmapPtr delete_bitmap = std::make_shared<DeleteBitmap>(self->tablet_id());
1923
19
    RETURN_IF_ERROR(self->calc_delete_bitmap_between_segments(
1924
19
            rowset->tablet_schema(), rowset->rowset_id(), segments, delete_bitmap));
1925
1926
    // get all base rowsets to calculate on
1927
19
    std::vector<RowsetSharedPtr> specified_rowsets;
1928
19
    RowsetIdUnorderedSet cur_rowset_ids;
1929
19
    if (specified_base_rowsets == nullptr) {
1930
19
        RETURN_IF_ERROR(self->get_all_rs_id_unlocked(cur_version - 1, &cur_rowset_ids));
1931
19
        specified_rowsets = self->get_rowset_by_ids(&cur_rowset_ids);
1932
19
    } else {
1933
0
        specified_rowsets = *specified_base_rowsets;
1934
0
    }
1935
1936
19
    OlapStopWatch watch;
1937
19
    auto token = self->calc_delete_bitmap_executor()->create_token();
1938
19
    RETURN_IF_ERROR(calc_delete_bitmap(self, rowset, segments, specified_rowsets, delete_bitmap,
1939
19
                                       cur_version - 1, token.get()));
1940
19
    RETURN_IF_ERROR(token->wait());
1941
19
    size_t total_rows = std::accumulate(
1942
19
            segments.begin(), segments.end(), 0,
1943
19
            [](size_t sum, const segment_v2::SegmentSharedPtr& s) { return sum += s->num_rows(); });
1944
19
    LOG(INFO) << "[Schema Change or Clone] construct delete bitmap tablet: " << self->tablet_id()
1945
19
              << ", rowset_ids: " << cur_rowset_ids.size() << ", cur max_version: " << cur_version
1946
19
              << ", transaction_id: " << -1 << ", cost: " << watch.get_elapse_time_us()
1947
19
              << "(us), total rows: " << total_rows;
1948
19
    if (config::enable_merge_on_write_correctness_check) {
1949
        // check if all the rowset has ROWSET_SENTINEL_MARK
1950
19
        auto st = self->check_delete_bitmap_correctness(delete_bitmap, cur_version - 1, -1,
1951
19
                                                        cur_rowset_ids, &specified_rowsets);
1952
19
        if (!st.ok()) {
1953
0
            LOG(WARNING) << fmt::format("delete bitmap correctness check failed in publish phase!");
1954
0
        }
1955
19
        delete_bitmap->remove_sentinel_marks();
1956
19
    }
1957
19
    for (auto& iter : delete_bitmap->delete_bitmap) {
1958
6
        self->_tablet_meta->delete_bitmap().merge(
1959
6
                {std::get<0>(iter.first), std::get<1>(iter.first), cur_version}, iter.second);
1960
6
    }
1961
1962
19
    return Status::OK();
1963
19
}
1964
1965
void BaseTablet::agg_delete_bitmap_for_stale_rowsets(
1966
6.19k
        Version version, DeleteBitmapKeyRanges& remove_delete_bitmap_key_ranges) {
1967
6.19k
    if (!config::enable_agg_and_remove_pre_rowsets_delete_bitmap) {
1968
0
        return;
1969
0
    }
1970
6.19k
    if (!(keys_type() == UNIQUE_KEYS && enable_unique_key_merge_on_write())) {
1971
0
        return;
1972
0
    }
1973
6.19k
    int64_t start_version = version.first;
1974
6.19k
    int64_t end_version = version.second;
1975
6.19k
    if (start_version == end_version) {
1976
0
        return;
1977
0
    }
1978
6.19k
    DCHECK(start_version < end_version)
1979
0
            << ". start_version: " << start_version << ", end_version: " << end_version;
1980
    // get pre rowsets
1981
6.19k
    std::vector<RowsetSharedPtr> pre_rowsets {};
1982
6.19k
    {
1983
6.19k
        std::shared_lock rdlock(_meta_lock);
1984
31.7k
        for (const auto& it2 : _rs_version_map) {
1985
31.7k
            if (it2.first.second < start_version) {
1986
6.98k
                pre_rowsets.emplace_back(it2.second);
1987
6.98k
            }
1988
31.7k
        }
1989
6.19k
    }
1990
6.19k
    std::sort(pre_rowsets.begin(), pre_rowsets.end(), Rowset::comparator);
1991
    // do agg for pre rowsets
1992
6.19k
    DeleteBitmapPtr new_delete_bitmap = std::make_shared<DeleteBitmap>(tablet_id());
1993
6.98k
    for (auto& rowset : pre_rowsets) {
1994
7.76k
        for (uint32_t seg_id = 0; seg_id < rowset->num_segments(); ++seg_id) {
1995
774
            auto d = tablet_meta()->delete_bitmap().get_agg_without_cache(
1996
774
                    {rowset->rowset_id(), seg_id, end_version}, start_version);
1997
774
            if (d->isEmpty()) {
1998
260
                continue;
1999
260
            }
2000
514
            VLOG_DEBUG << "agg delete bitmap for tablet_id=" << tablet_id()
2001
0
                       << ", rowset_id=" << rowset->rowset_id() << ", seg_id=" << seg_id
2002
0
                       << ", rowset_version=" << rowset->version().to_string()
2003
0
                       << ". compaction start_version=" << start_version
2004
0
                       << ", end_version=" << end_version << ", delete_bitmap=" << d->cardinality();
2005
514
            DeleteBitmap::BitmapKey start_key {rowset->rowset_id(), seg_id, start_version};
2006
514
            DeleteBitmap::BitmapKey end_key {rowset->rowset_id(), seg_id, end_version};
2007
514
            new_delete_bitmap->set(end_key, *d);
2008
514
            remove_delete_bitmap_key_ranges.emplace_back(start_key, end_key);
2009
514
        }
2010
6.98k
    }
2011
6.19k
    DBUG_EXECUTE_IF("BaseTablet.agg_delete_bitmap_for_stale_rowsets.merge_delete_bitmap.block",
2012
6.19k
                    DBUG_BLOCK);
2013
6.19k
    tablet_meta()->delete_bitmap().merge(*new_delete_bitmap);
2014
6.19k
}
2015
2016
void BaseTablet::check_agg_delete_bitmap_for_stale_rowsets(int64_t& useless_rowset_count,
2017
0
                                                           int64_t& useless_rowset_version_count) {
2018
0
    std::map<RowsetId, Version> rowset_ids;
2019
0
    std::set<int64_t> end_versions;
2020
0
    traverse_rowsets(
2021
0
            [&rowset_ids, &end_versions](const RowsetSharedPtr& rs) {
2022
0
                rowset_ids[rs->rowset_id()] = rs->version();
2023
0
                end_versions.emplace(rs->end_version());
2024
0
            },
2025
0
            true);
2026
2027
0
    std::set<RowsetId> useless_rowsets;
2028
0
    std::map<RowsetId, std::vector<int64_t>> useless_rowset_versions;
2029
0
    {
2030
0
        _tablet_meta->delete_bitmap().traverse_rowset_and_version(
2031
                // 0: rowset and rowset with version exists
2032
                // -1: rowset does not exist
2033
                // -2: find next <rowset, version>
2034
                //     rowset exist, rowset with version does not exist
2035
                //     sequence table
2036
0
                [&](const RowsetId& rowset_id, int64_t version) {
2037
0
                    auto rowset_it = rowset_ids.find(rowset_id);
2038
0
                    if (rowset_it == rowset_ids.end()) {
2039
0
                        useless_rowsets.emplace(rowset_id);
2040
0
                        return -1;
2041
0
                    }
2042
0
                    if (end_versions.find(version) == end_versions.end()) {
2043
0
                        if (tablet_schema()->has_sequence_col()) {
2044
0
                            auto rowset_version = rowset_it->second;
2045
0
                            if (version >= rowset_version.first &&
2046
0
                                version <= rowset_version.second) {
2047
0
                                return -2;
2048
0
                            }
2049
0
                        }
2050
0
                        if (useless_rowset_versions.find(rowset_id) ==
2051
0
                            useless_rowset_versions.end()) {
2052
0
                            useless_rowset_versions[rowset_id] = {};
2053
0
                        }
2054
0
                        useless_rowset_versions[rowset_id].emplace_back(version);
2055
0
                        return -2;
2056
0
                    }
2057
0
                    return 0;
2058
0
                });
2059
0
    }
2060
0
    useless_rowset_count = useless_rowsets.size();
2061
0
    useless_rowset_version_count = useless_rowset_versions.size();
2062
0
    if (!useless_rowsets.empty() || !useless_rowset_versions.empty()) {
2063
0
        std::stringstream ss;
2064
0
        if (!useless_rowsets.empty()) {
2065
0
            ss << "useless rowsets: {";
2066
0
            for (auto it = useless_rowsets.begin(); it != useless_rowsets.end(); ++it) {
2067
0
                if (it != useless_rowsets.begin()) {
2068
0
                    ss << ", ";
2069
0
                }
2070
0
                ss << it->to_string();
2071
0
            }
2072
0
            ss << "}. ";
2073
0
        }
2074
0
        if (!useless_rowset_versions.empty()) {
2075
0
            ss << "useless rowset versions: {";
2076
0
            for (auto iter = useless_rowset_versions.begin(); iter != useless_rowset_versions.end();
2077
0
                 ++iter) {
2078
0
                if (iter != useless_rowset_versions.begin()) {
2079
0
                    ss << ", ";
2080
0
                }
2081
0
                ss << iter->first.to_string() << ": [";
2082
                // some versions are continuous, such as [8, 9, 10, 11, 13, 17, 18]
2083
                // print as [8-11, 13, 17-18]
2084
0
                int64_t last_start_version = -1;
2085
0
                int64_t last_end_version = -1;
2086
0
                for (int64_t version : iter->second) {
2087
0
                    if (last_start_version == -1) {
2088
0
                        last_start_version = version;
2089
0
                        last_end_version = version;
2090
0
                        continue;
2091
0
                    }
2092
0
                    if (last_end_version + 1 == version) {
2093
0
                        last_end_version = version;
2094
0
                    } else {
2095
0
                        if (last_start_version == last_end_version) {
2096
0
                            ss << last_start_version << ", ";
2097
0
                        } else {
2098
0
                            ss << last_start_version << "-" << last_end_version << ", ";
2099
0
                        }
2100
0
                        last_start_version = version;
2101
0
                        last_end_version = version;
2102
0
                    }
2103
0
                }
2104
0
                if (last_start_version == last_end_version) {
2105
0
                    ss << last_start_version;
2106
0
                } else {
2107
0
                    ss << last_start_version << "-" << last_end_version;
2108
0
                }
2109
2110
0
                ss << "]";
2111
0
            }
2112
0
            ss << "}.";
2113
0
        }
2114
0
        LOG(WARNING) << "failed check_agg_delete_bitmap_for_stale_rowsets for tablet_id="
2115
0
                     << tablet_id() << ". " << ss.str();
2116
0
    } else {
2117
0
        LOG(INFO) << "succeed check_agg_delete_bitmap_for_stale_rowsets for tablet_id="
2118
0
                  << tablet_id();
2119
0
    }
2120
0
}
2121
2122
7
RowsetSharedPtr BaseTablet::get_rowset(const RowsetId& rowset_id) {
2123
7
    std::shared_lock rdlock(_meta_lock);
2124
11
    for (auto& version_rowset : _rs_version_map) {
2125
11
        if (version_rowset.second->rowset_id() == rowset_id) {
2126
7
            return version_rowset.second;
2127
7
        }
2128
11
    }
2129
0
    for (auto& stale_version_rowset : _stale_rs_version_map) {
2130
0
        if (stale_version_rowset.second->rowset_id() == rowset_id) {
2131
0
            return stale_version_rowset.second;
2132
0
        }
2133
0
    }
2134
0
    return nullptr;
2135
0
}
2136
2137
1.69k
std::vector<RowsetSharedPtr> BaseTablet::get_snapshot_rowset(bool include_stale_rowset) const {
2138
1.69k
    std::shared_lock rdlock(_meta_lock);
2139
1.69k
    std::vector<RowsetSharedPtr> rowsets;
2140
1.69k
    std::transform(_rs_version_map.cbegin(), _rs_version_map.cend(), std::back_inserter(rowsets),
2141
5.74k
                   [](auto& kv) { return kv.second; });
2142
1.69k
    if (include_stale_rowset) {
2143
274
        std::transform(_stale_rs_version_map.cbegin(), _stale_rs_version_map.cend(),
2144
303
                       std::back_inserter(rowsets), [](auto& kv) { return kv.second; });
2145
274
    }
2146
1.69k
    return rowsets;
2147
1.69k
}
2148
2149
void BaseTablet::calc_consecutive_empty_rowsets(
2150
        std::vector<RowsetSharedPtr>* empty_rowsets,
2151
373
        const std::vector<RowsetSharedPtr>& candidate_rowsets, int64_t limit) {
2152
373
    int len = cast_set<int>(candidate_rowsets.size());
2153
417
    for (int i = 0; i < len - 1; ++i) {
2154
48
        auto rowset = candidate_rowsets[i];
2155
48
        auto next_rowset = candidate_rowsets[i + 1];
2156
2157
        // identify two consecutive rowsets that are empty
2158
48
        if (rowset->num_segments() == 0 && next_rowset->num_segments() == 0 &&
2159
48
            !rowset->rowset_meta()->has_delete_predicate() &&
2160
48
            !next_rowset->rowset_meta()->has_delete_predicate() &&
2161
48
            rowset->end_version() == next_rowset->start_version() - 1) {
2162
4
            empty_rowsets->emplace_back(rowset);
2163
4
            empty_rowsets->emplace_back(next_rowset);
2164
4
            rowset = next_rowset;
2165
4
            int next_index = i + 2;
2166
2167
            // keep searching for consecutive empty rowsets
2168
18
            while (next_index < len && candidate_rowsets[next_index]->num_segments() == 0 &&
2169
18
                   !candidate_rowsets[next_index]->rowset_meta()->has_delete_predicate() &&
2170
18
                   rowset->end_version() == candidate_rowsets[next_index]->start_version() - 1) {
2171
14
                empty_rowsets->emplace_back(candidate_rowsets[next_index]);
2172
14
                rowset = candidate_rowsets[next_index++];
2173
14
            }
2174
            // if the number of consecutive empty rowset reach the limit,
2175
            // and there are still rowsets following them
2176
4
            if (empty_rowsets->size() >= limit && next_index < len) {
2177
4
                return;
2178
4
            } else {
2179
                // current rowset is not empty, start searching from that rowset in the next
2180
0
                i = next_index - 1;
2181
0
                empty_rowsets->clear();
2182
0
            }
2183
4
        }
2184
48
    }
2185
373
}
2186
2187
Status BaseTablet::calc_file_crc(uint32_t* crc_value, int64_t start_version, int64_t end_version,
2188
2
                                 uint32_t* rowset_count, int64_t* file_count) {
2189
2
    Version v(start_version, end_version);
2190
2
    std::vector<RowsetSharedPtr> rowsets;
2191
10
    traverse_rowsets([&rowsets, &v](const auto& rs) {
2192
        // get all rowsets
2193
10
        if (v.contains(rs->version())) {
2194
10
            rowsets.emplace_back(rs);
2195
10
        }
2196
10
    });
2197
2
    std::sort(rowsets.begin(), rowsets.end(), Rowset::comparator);
2198
2
    *rowset_count = cast_set<uint32_t>(rowsets.size());
2199
2200
2
    *crc_value = 0;
2201
2
    *file_count = 0;
2202
10
    for (const auto& rs : rowsets) {
2203
10
        uint32_t rs_crc_value = 0;
2204
10
        int64_t rs_file_count = 0;
2205
10
        auto rowset = std::static_pointer_cast<BetaRowset>(rs);
2206
10
        auto st = rowset->calc_file_crc(&rs_crc_value, &rs_file_count);
2207
10
        if (!st.ok()) {
2208
0
            return st;
2209
0
        }
2210
        // crc_value is calculated based on the crc_value of each rowset.
2211
10
        *crc_value = crc32c::Extend(*crc_value, reinterpret_cast<const uint8_t*>(&rs_crc_value),
2212
10
                                    sizeof(rs_crc_value));
2213
10
        *file_count += rs_file_count;
2214
10
    }
2215
2
    return Status::OK();
2216
2
}
2217
2218
48
Status BaseTablet::show_nested_index_file(std::string* json_meta) {
2219
48
    Version v(0, max_version_unlocked());
2220
48
    std::vector<RowsetSharedPtr> rowsets;
2221
147
    traverse_rowsets([&rowsets, &v](const auto& rs) {
2222
        // get all rowsets
2223
147
        if (v.contains(rs->version())) {
2224
147
            rowsets.emplace_back(rs);
2225
147
        }
2226
147
    });
2227
48
    std::sort(rowsets.begin(), rowsets.end(), Rowset::comparator);
2228
2229
48
    rapidjson::Document doc;
2230
48
    doc.SetObject();
2231
48
    rapidjson::Document::AllocatorType& allocator = doc.GetAllocator();
2232
48
    rapidjson::Value tabletIdValue(tablet_id());
2233
48
    doc.AddMember("tablet_id", tabletIdValue, allocator);
2234
2235
48
    rapidjson::Value rowsets_value(rapidjson::kArrayType);
2236
2237
147
    for (const auto& rs : rowsets) {
2238
147
        rapidjson::Value rowset_value(rapidjson::kObjectType);
2239
2240
147
        auto rowset = std::static_pointer_cast<BetaRowset>(rs);
2241
147
        RETURN_IF_ERROR(rowset->show_nested_index_file(&rowset_value, allocator));
2242
146
        rowsets_value.PushBack(rowset_value, allocator);
2243
146
    }
2244
47
    doc.AddMember("rowsets", rowsets_value, allocator);
2245
2246
47
    rapidjson::StringBuffer buffer;
2247
47
    rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(buffer);
2248
47
    doc.Accept(writer);
2249
47
    *json_meta = std::string(buffer.GetString());
2250
2251
47
    return Status::OK();
2252
48
}
2253
2254
void BaseTablet::get_base_rowset_delete_bitmap_count(
2255
        uint64_t* max_base_rowset_delete_bitmap_score,
2256
430
        int64_t* max_base_rowset_delete_bitmap_score_tablet_id) {
2257
430
    std::vector<RowsetSharedPtr> rowsets_;
2258
430
    std::string base_rowset_id_str;
2259
430
    {
2260
430
        std::shared_lock rowset_ldlock(this->get_header_lock());
2261
4.88k
        for (const auto& it : _rs_version_map) {
2262
4.88k
            rowsets_.emplace_back(it.second);
2263
4.88k
        }
2264
430
    }
2265
430
    std::sort(rowsets_.begin(), rowsets_.end(), Rowset::comparator);
2266
430
    if (!rowsets_.empty()) {
2267
430
        bool base_found = false;
2268
981
        for (auto& rowset : rowsets_) {
2269
981
            if (rowset->start_version() > 2) {
2270
221
                break;
2271
221
            }
2272
760
            base_found = true;
2273
760
            uint64_t base_rowset_delete_bitmap_count =
2274
760
                    this->tablet_meta()->delete_bitmap().get_count_with_range(
2275
760
                            {rowset->rowset_id(), 0, 0},
2276
760
                            {rowset->rowset_id(), UINT32_MAX, UINT64_MAX});
2277
760
            if (base_rowset_delete_bitmap_count > *max_base_rowset_delete_bitmap_score) {
2278
36
                *max_base_rowset_delete_bitmap_score = base_rowset_delete_bitmap_count;
2279
36
                *max_base_rowset_delete_bitmap_score_tablet_id = this->tablet_id();
2280
36
            }
2281
760
        }
2282
430
        if (!base_found) {
2283
0
            LOG(WARNING) << "can not found base rowset for tablet " << tablet_id();
2284
0
        }
2285
430
    }
2286
430
}
2287
2288
1.52M
void TabletReadSource::fill_delete_predicates() {
2289
1.52M
    DCHECK_EQ(delete_predicates.size(), 0);
2290
1.52M
    auto delete_pred_view =
2291
6.29M
            rs_splits | std::views::transform([](auto&& split) {
2292
6.29M
                return split.rs_reader->rowset()->rowset_meta();
2293
6.29M
            }) |
2294
6.32M
            std::views::filter([](const auto& rs_meta) { return rs_meta->has_delete_predicate(); });
2295
1.52M
    delete_predicates = {delete_pred_view.begin(), delete_pred_view.end()};
2296
1.52M
}
2297
2298
314M
int32_t BaseTablet::max_version_config() {
2299
314M
    int32_t max_version = tablet_meta()->compaction_policy() == CUMULATIVE_TIME_SERIES_POLICY
2300
314M
                                  ? std::max(config::time_series_max_tablet_version_num,
2301
4.07k
                                             config::max_tablet_version_num)
2302
314M
                                  : config::max_tablet_version_num;
2303
314M
    return max_version;
2304
314M
}
2305
2306
24.8k
void BaseTablet::prefill_dbm_agg_cache(const RowsetSharedPtr& rowset, int64_t version) {
2307
37.3k
    for (std::size_t i = 0; i < rowset->num_segments(); i++) {
2308
12.5k
        tablet_meta()->delete_bitmap().get_agg({rowset->rowset_id(), i, version});
2309
12.5k
    }
2310
24.8k
}
2311
2312
10.3k
void BaseTablet::prefill_dbm_agg_cache_after_compaction(const RowsetSharedPtr& output_rowset) {
2313
10.3k
    if (keys_type() == KeysType::UNIQUE_KEYS && enable_unique_key_merge_on_write() &&
2314
10.3k
        (config::enable_prefill_output_dbm_agg_cache_after_compaction ||
2315
6.30k
         config::enable_prefill_all_dbm_agg_cache_after_compaction)) {
2316
6.30k
        int64_t cur_max_version {-1};
2317
6.30k
        {
2318
6.30k
            std::shared_lock rlock(get_header_lock());
2319
6.30k
            cur_max_version = max_version_unlocked();
2320
6.30k
        }
2321
6.30k
        if (config::enable_prefill_all_dbm_agg_cache_after_compaction) {
2322
6.30k
            traverse_rowsets(
2323
24.8k
                    [&](const RowsetSharedPtr& rs) { prefill_dbm_agg_cache(rs, cur_max_version); },
2324
6.30k
                    false);
2325
6.30k
        } else if (config::enable_prefill_output_dbm_agg_cache_after_compaction) {
2326
0
            prefill_dbm_agg_cache(output_rowset, cur_max_version);
2327
0
        }
2328
6.30k
    }
2329
10.3k
}
2330
2331
bool BaseTablet::_key_is_not_in_segment(Slice key, const KeyBoundsPB& segment_key_bounds,
2332
3.98M
                                        bool is_segments_key_bounds_truncated) {
2333
3.98M
    Slice maybe_truncated_min_key {segment_key_bounds.min_key()};
2334
3.98M
    Slice maybe_truncated_max_key {segment_key_bounds.max_key()};
2335
3.98M
    bool res1 = Slice::lhs_is_strictly_less_than_rhs(key, false, maybe_truncated_min_key,
2336
3.98M
                                                     is_segments_key_bounds_truncated);
2337
3.98M
    bool res2 = Slice::lhs_is_strictly_less_than_rhs(maybe_truncated_max_key,
2338
3.98M
                                                     is_segments_key_bounds_truncated, key, false);
2339
3.98M
    return res1 || res2;
2340
3.98M
}
2341
2342
} // namespace doris