Coverage Report

Created: 2026-05-14 05:50

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