Coverage Report

Created: 2026-08-14 13:39

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