Coverage Report

Created: 2024-11-22 21:49

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