Coverage Report

Created: 2025-09-11 19:59

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