Coverage Report

Created: 2026-07-15 14:38

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