Coverage Report

Created: 2025-09-12 17:50

/root/doris/be/src/olap/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/tablet.h"
19
20
#include <butil/logging.h>
21
#include <bvar/reducer.h>
22
#include <bvar/window.h>
23
#include <fmt/format.h>
24
#include <gen_cpp/FrontendService_types.h>
25
#include <gen_cpp/MasterService_types.h>
26
#include <gen_cpp/Metrics_types.h>
27
#include <gen_cpp/olap_file.pb.h>
28
#include <gen_cpp/types.pb.h>
29
#include <glog/logging.h>
30
#include <rapidjson/document.h>
31
#include <rapidjson/encodings.h>
32
#include <rapidjson/prettywriter.h>
33
#include <rapidjson/rapidjson.h>
34
#include <rapidjson/stringbuffer.h>
35
36
#include <algorithm>
37
#include <atomic>
38
#include <boost/container/detail/std_fwd.hpp>
39
#include <cstdint>
40
#include <roaring/roaring.hh>
41
42
#include "common/compiler_util.h" // IWYU pragma: keep
43
// IWYU pragma: no_include <bits/chrono.h>
44
#include <chrono> // IWYU pragma: keep
45
#include <filesystem>
46
#include <iterator>
47
#include <limits>
48
#include <map>
49
#include <memory>
50
#include <mutex>
51
#include <set>
52
#include <shared_mutex>
53
#include <string>
54
#include <tuple>
55
#include <type_traits>
56
#include <unordered_map>
57
#include <unordered_set>
58
59
#include "agent/utils.h"
60
#include "common/config.h"
61
#include "common/consts.h"
62
#include "common/exception.h"
63
#include "common/logging.h"
64
#include "common/signal_handler.h"
65
#include "common/status.h"
66
#include "exprs/runtime_filter.h"
67
#include "gutil/ref_counted.h"
68
#include "gutil/strings/substitute.h"
69
#include "io/fs/file_reader.h"
70
#include "io/fs/file_reader_writer_fwd.h"
71
#include "io/fs/file_system.h"
72
#include "io/fs/file_writer.h"
73
#include "io/fs/path.h"
74
#include "io/fs/remote_file_system.h"
75
#include "io/io_common.h"
76
#include "olap/base_compaction.h"
77
#include "olap/base_tablet.h"
78
#include "olap/binlog.h"
79
#include "olap/cumulative_compaction.h"
80
#include "olap/cumulative_compaction_policy.h"
81
#include "olap/cumulative_compaction_time_series_policy.h"
82
#include "olap/delete_bitmap_calculator.h"
83
#include "olap/full_compaction.h"
84
#include "olap/memtable.h"
85
#include "olap/olap_common.h"
86
#include "olap/olap_define.h"
87
#include "olap/olap_meta.h"
88
#include "olap/primary_key_index.h"
89
#include "olap/rowset/beta_rowset.h"
90
#include "olap/rowset/rowset.h"
91
#include "olap/rowset/rowset_factory.h"
92
#include "olap/rowset/rowset_fwd.h"
93
#include "olap/rowset/rowset_meta.h"
94
#include "olap/rowset/rowset_meta_manager.h"
95
#include "olap/rowset/rowset_writer.h"
96
#include "olap/rowset/rowset_writer_context.h"
97
#include "olap/rowset/segment_v2/column_reader.h"
98
#include "olap/rowset/segment_v2/common.h"
99
#include "olap/rowset/segment_v2/indexed_column_reader.h"
100
#include "olap/rowset/vertical_beta_rowset_writer.h"
101
#include "olap/schema_change.h"
102
#include "olap/single_replica_compaction.h"
103
#include "olap/storage_engine.h"
104
#include "olap/storage_policy.h"
105
#include "olap/tablet_manager.h"
106
#include "olap/tablet_meta.h"
107
#include "olap/tablet_meta_manager.h"
108
#include "olap/tablet_schema.h"
109
#include "olap/txn_manager.h"
110
#include "olap/types.h"
111
#include "olap/utils.h"
112
#include "segment_loader.h"
113
#include "service/point_query_executor.h"
114
#include "tablet.h"
115
#include "util/bvar_helper.h"
116
#include "util/debug_points.h"
117
#include "util/defer_op.h"
118
#include "util/doris_metrics.h"
119
#include "util/pretty_printer.h"
120
#include "util/scoped_cleanup.h"
121
#include "util/stopwatch.hpp"
122
#include "util/threadpool.h"
123
#include "util/time.h"
124
#include "util/trace.h"
125
#include "util/uid_util.h"
126
#include "util/work_thread_pool.hpp"
127
#include "vec/columns/column.h"
128
#include "vec/columns/column_string.h"
129
#include "vec/common/schema_util.h"
130
#include "vec/common/string_ref.h"
131
#include "vec/data_types/data_type.h"
132
#include "vec/data_types/data_type_factory.hpp"
133
#include "vec/data_types/serde/data_type_serde.h"
134
#include "vec/jsonb/serialize.h"
135
136
namespace doris {
137
class TupleDescriptor;
138
139
namespace vectorized {
140
class Block;
141
} // namespace vectorized
142
143
using namespace ErrorCode;
144
using namespace std::chrono_literals;
145
146
using std::pair;
147
using std::string;
148
using std::vector;
149
using io::FileSystemSPtr;
150
151
namespace {
152
153
bvar::Adder<uint64_t> exceed_version_limit_counter;
154
bvar::Window<bvar::Adder<uint64_t>> exceed_version_limit_counter_minute(
155
        &exceed_version_limit_counter, 60);
156
bvar::Adder<uint64_t> cooldown_pending_task("cooldown_pending_task");
157
bvar::Adder<uint64_t> cooldown_processing_task("cooldown_processing_task");
158
159
1
void set_last_failure_time(Tablet* tablet, const Compaction& compaction, int64_t ms) {
160
1
    switch (compaction.compaction_type()) {
161
1
    case ReaderType::READER_CUMULATIVE_COMPACTION:
  Branch (161:5): [True: 1, False: 0]
162
1
        tablet->set_last_cumu_compaction_failure_time(ms);
163
1
        return;
164
0
    case ReaderType::READER_BASE_COMPACTION:
  Branch (164:5): [True: 0, False: 1]
165
0
        tablet->set_last_base_compaction_failure_time(ms);
166
0
        return;
167
0
    case ReaderType::READER_FULL_COMPACTION:
  Branch (167:5): [True: 0, False: 1]
168
0
        tablet->set_last_full_compaction_failure_time(ms);
169
0
        return;
170
0
    default:
  Branch (170:5): [True: 0, False: 1]
171
0
        LOG(FATAL) << "invalid compaction type " << compaction.compaction_name()
172
0
                   << " tablet_id: " << tablet->tablet_id();
173
1
    }
174
1
};
175
176
} // namespace
177
178
bvar::Adder<uint64_t> unused_remote_rowset_num("unused_remote_rowset_num");
179
180
WriteCooldownMetaExecutors::WriteCooldownMetaExecutors(size_t executor_nums)
181
1
        : _executor_nums(executor_nums) {
182
6
    for (size_t i = 0; i < _executor_nums; i++) {
  Branch (182:24): [True: 5, False: 1]
183
5
        std::unique_ptr<PriorityThreadPool> pool;
184
5
        static_cast<void>(ThreadPoolBuilder("WriteCooldownMetaExecutor")
185
5
                                  .set_min_threads(1)
186
5
                                  .set_max_threads(1)
187
5
                                  .set_max_queue_size(std::numeric_limits<int>::max())
188
5
                                  .build(&pool));
189
5
        _executors.emplace_back(std::move(pool));
190
5
    }
191
1
}
192
193
0
void WriteCooldownMetaExecutors::stop() {
194
0
    for (auto& pool_ptr : _executors) {
  Branch (194:25): [True: 0, False: 0]
195
0
        if (pool_ptr) {
  Branch (195:13): [True: 0, False: 0]
196
0
            pool_ptr->shutdown();
197
0
        }
198
0
    }
199
0
}
200
201
5
void WriteCooldownMetaExecutors::WriteCooldownMetaExecutors::submit(TabletSharedPtr tablet) {
202
5
    auto tablet_id = tablet->tablet_id();
203
204
5
    {
205
5
        std::shared_lock rdlock(tablet->get_header_lock());
206
5
        if (!tablet->tablet_meta()->cooldown_meta_id().initialized()) {
  Branch (206:13): [True: 0, False: 5]
207
0
            VLOG_NOTICE << "tablet " << tablet_id << " is not cooldown replica";
Line
Count
Source
42
0
#define VLOG_NOTICE VLOG(3)
208
0
            return;
209
0
        }
210
5
        if (tablet->tablet_state() == TABLET_SHUTDOWN) [[unlikely]] {
  Branch (210:13): [True: 0, False: 5]
211
0
            LOG_INFO("tablet {} has been dropped, don't do cooldown", tablet_id);
Line
Count
Source
118
0
#define LOG_INFO TaggableLogger(__FILE__, __LINE__, google::GLOG_INFO)
212
0
            return;
213
0
        }
214
5
    }
215
5
    {
216
        // one tablet could at most have one cooldown task to be done
217
5
        std::unique_lock<std::mutex> lck {_latch};
218
5
        if (_pending_tablets.count(tablet_id) > 0) {
  Branch (218:13): [True: 0, False: 5]
219
0
            return;
220
0
        }
221
5
        _pending_tablets.insert(tablet_id);
222
5
    }
223
224
5
    auto async_write_task = [this, t = std::move(tablet)]() {
225
5
        {
226
5
            std::unique_lock<std::mutex> lck {_latch};
227
5
            _pending_tablets.erase(t->tablet_id());
228
5
        }
229
5
        auto s = t->write_cooldown_meta();
230
5
        if (s.ok()) {
  Branch (230:13): [True: 5, False: 0]
231
5
            return;
232
5
        }
233
0
        if (!s.is<ABORTED>()) {
  Branch (233:13): [True: 0, False: 0]
234
0
            LOG_EVERY_SECOND(WARNING)
235
0
                    << "write tablet " << t->tablet_id() << " cooldown meta failed because: " << s;
236
0
            submit(t);
237
0
            return;
238
0
        }
239
0
        VLOG_DEBUG << "tablet " << t->tablet_id() << " is not cooldown replica";
Line
Count
Source
41
0
#define VLOG_DEBUG VLOG(7)
240
0
    };
241
242
5
    cooldown_pending_task << 1;
243
5
    _executors[_get_executor_pos(tablet_id)]->offer([task = std::move(async_write_task)]() {
244
5
        cooldown_pending_task << -1;
245
5
        cooldown_processing_task << 1;
246
5
        task();
247
5
        cooldown_processing_task << -1;
248
5
    });
249
5
}
250
251
Tablet::Tablet(StorageEngine& engine, TabletMetaSharedPtr tablet_meta, DataDir* data_dir,
252
               const std::string_view& cumulative_compaction_type)
253
        : BaseTablet(std::move(tablet_meta)),
254
          _engine(engine),
255
          _data_dir(data_dir),
256
          _is_bad(false),
257
          _last_cumu_compaction_failure_millis(0),
258
          _last_base_compaction_failure_millis(0),
259
          _last_full_compaction_failure_millis(0),
260
          _last_cumu_compaction_success_millis(0),
261
          _last_base_compaction_success_millis(0),
262
          _last_full_compaction_success_millis(0),
263
          _cumulative_point(K_INVALID_CUMULATIVE_POINT),
264
          _newly_created_rowset_num(0),
265
          _last_checkpoint_time(0),
266
          _cumulative_compaction_type(cumulative_compaction_type),
267
          _is_tablet_path_exists(true),
268
          _last_missed_version(-1),
269
577
          _last_missed_time_s(0) {
270
577
    if (_data_dir != nullptr) {
  Branch (270:9): [True: 440, False: 137]
271
440
        _tablet_path = fmt::format("{}/{}/{}/{}/{}", _data_dir->path(), DATA_PREFIX,
272
440
                                   _tablet_meta->shard_id(), tablet_id(), schema_hash());
273
440
    }
274
577
}
275
276
0
bool Tablet::set_tablet_schema_into_rowset_meta() {
277
0
    bool flag = false;
278
0
    for (auto&& rowset_meta : _tablet_meta->all_mutable_rs_metas()) {
  Branch (278:29): [True: 0, False: 0]
279
0
        if (!rowset_meta->tablet_schema()) {
  Branch (279:13): [True: 0, False: 0]
280
0
            rowset_meta->set_tablet_schema(_tablet_meta->tablet_schema());
281
0
            flag = true;
282
0
        }
283
0
    }
284
0
    return flag;
285
0
}
286
287
539
Status Tablet::_init_once_action() {
288
539
    Status res = Status::OK();
289
539
    VLOG_NOTICE << "begin to load tablet. tablet=" << tablet_id()
Line
Count
Source
42
0
#define VLOG_NOTICE VLOG(3)
290
0
                << ", version_size=" << _tablet_meta->version_count();
291
292
539
#ifdef BE_TEST
293
    // init cumulative compaction policy by type
294
539
    _cumulative_compaction_policy =
295
539
            CumulativeCompactionPolicyFactory::create_cumulative_compaction_policy(
296
539
                    _tablet_meta->compaction_policy());
297
539
#endif
298
299
539
    for (const auto& rs_meta : _tablet_meta->all_rs_metas()) {
  Branch (299:30): [True: 200, False: 539]
300
200
        Version version = rs_meta->version();
301
200
        RowsetSharedPtr rowset;
302
200
        res = create_rowset(rs_meta, &rowset);
303
200
        if (!res.ok()) {
  Branch (303:13): [True: 0, False: 200]
304
0
            LOG(WARNING) << "fail to init rowset. tablet_id=" << tablet_id()
305
0
                         << ", schema_hash=" << schema_hash() << ", version=" << version
306
0
                         << ", res=" << res;
307
0
            return res;
308
0
        }
309
200
        _rs_version_map[version] = std::move(rowset);
310
200
    }
311
312
    // init stale rowset
313
539
    int64_t now = ::time(nullptr);
314
539
    for (const auto& stale_rs_meta : _tablet_meta->all_stale_rs_metas()) {
  Branch (314:36): [True: 0, False: 539]
315
0
        Version version = stale_rs_meta->version();
316
317
0
        if (!stale_rs_meta->has_stale_at()) {
  Branch (317:13): [True: 0, False: 0]
318
0
            stale_rs_meta->set_stale_at(now);
319
0
        }
320
321
0
        RowsetSharedPtr rowset;
322
0
        res = create_rowset(stale_rs_meta, &rowset);
323
0
        if (!res.ok()) {
  Branch (323:13): [True: 0, False: 0]
324
0
            LOG(WARNING) << "fail to init stale rowset. tablet_id:" << tablet_id()
325
0
                         << ", schema_hash:" << schema_hash() << ", version=" << version
326
0
                         << ", res:" << res;
327
0
            return res;
328
0
        }
329
0
        _stale_rs_version_map[version] = std::move(rowset);
330
0
    }
331
332
539
    return res;
333
539
}
334
335
766
Status Tablet::init() {
336
766
    return _init_once.call([this] { return _init_once_action(); });
337
766
}
338
339
// should save tablet meta to remote meta store
340
// if it's a primary replica
341
565
void Tablet::save_meta() {
342
565
    check_table_size_correctness();
343
565
    auto res = _tablet_meta->save_meta(_data_dir);
344
565
    CHECK_EQ(res, Status::OK()) << "fail to save tablet_meta. res=" << res
345
0
                                << ", root=" << _data_dir->path();
346
565
}
347
348
// Caller should hold _meta_lock.
349
Status Tablet::revise_tablet_meta(const std::vector<RowsetSharedPtr>& to_add,
350
                                  const std::vector<RowsetSharedPtr>& to_delete,
351
0
                                  bool is_incremental_clone) {
352
0
    LOG(INFO) << "begin to revise tablet. tablet_id=" << tablet_id();
353
    // 1. for incremental clone, we have to add the rowsets first to make it easy to compute
354
    //    all the delete bitmaps, and it's easy to delete them if we end up with a failure
355
    // 2. for full clone, we can calculate delete bitmaps on the cloned rowsets directly.
356
0
    if (is_incremental_clone) {
  Branch (356:9): [True: 0, False: 0]
357
0
        CHECK(to_delete.empty()); // don't need to delete rowsets
358
0
        add_rowsets(to_add);
359
        // reconstruct from tablet meta
360
0
        _timestamped_version_tracker.construct_versioned_tracker(_tablet_meta->all_rs_metas());
361
0
    }
362
363
0
    Status calc_bm_status;
364
0
    std::vector<RowsetSharedPtr> base_rowsets_for_full_clone = to_add; // copy vector
365
0
    while (keys_type() == UNIQUE_KEYS && enable_unique_key_merge_on_write()) {
  Branch (365:12): [True: 0, False: 0]
  Branch (365:42): [True: 0, False: 0]
366
0
        std::vector<RowsetSharedPtr> calc_delete_bitmap_rowsets;
367
0
        int64_t to_add_min_version = INT64_MAX;
368
0
        int64_t to_add_max_version = INT64_MIN;
369
0
        for (auto& rs : to_add) {
  Branch (369:23): [True: 0, False: 0]
370
0
            if (to_add_min_version > rs->start_version()) {
  Branch (370:17): [True: 0, False: 0]
371
0
                to_add_min_version = rs->start_version();
372
0
            }
373
0
            if (to_add_max_version < rs->end_version()) {
  Branch (373:17): [True: 0, False: 0]
374
0
                to_add_max_version = rs->end_version();
375
0
            }
376
0
        }
377
0
        Version calc_delete_bitmap_ver;
378
0
        if (is_incremental_clone) {
  Branch (378:13): [True: 0, False: 0]
379
            // From the rowset of to_add with smallest version, all other rowsets
380
            // need to recalculate the delete bitmap
381
            // For example:
382
            // local tablet: [0-1] [2-5] [6-6] [9-10]
383
            // clone tablet: [7-7] [8-8]
384
            // new tablet:   [0-1] [2-5] [6-6] [7-7] [8-8] [9-10]
385
            // [7-7] [8-8] [9-10] need to recalculate delete bitmap
386
0
            calc_delete_bitmap_ver = Version(to_add_min_version, max_version_unlocked());
387
0
        } else {
388
            // the delete bitmap of to_add's rowsets has clone from remote when full clone.
389
            // only other rowsets in local need to recalculate the delete bitmap.
390
            // For example:
391
            // local tablet: [0-1]x [2-5]x [6-6]x [7-7]x [9-10]
392
            // clone tablet: [0-1]  [2-4]  [5-6]  [7-8]
393
            // new tablet:   [0-1]  [2-4]  [5-6]  [7-8] [9-10]
394
            // only [9-10] need to recalculate delete bitmap
395
0
            CHECK_EQ(to_add_min_version, 0) << "to_add_min_version is: " << to_add_min_version;
396
0
            calc_delete_bitmap_ver = Version(to_add_max_version + 1, max_version_unlocked());
397
0
        }
398
399
0
        if (calc_delete_bitmap_ver.first <= calc_delete_bitmap_ver.second) {
  Branch (399:13): [True: 0, False: 0]
400
0
            auto ret = capture_consistent_rowsets_unlocked(calc_delete_bitmap_ver,
401
0
                                                           CaptureRowsetOps {});
402
0
            if (!ret) {
  Branch (402:17): [True: 0, False: 0]
403
0
                LOG(WARNING) << "fail to capture_consistent_rowsets, res: " << ret.error();
404
0
                calc_bm_status = std::move(ret.error());
405
0
                break;
406
0
            }
407
0
            calc_delete_bitmap_rowsets = std::move(ret->rowsets);
408
            // FIXME(plat1ko): Use `const TabletSharedPtr&` as parameter
409
0
            auto self = _engine.tablet_manager()->get_tablet(tablet_id());
410
0
            CHECK(self);
411
0
            for (auto rs : calc_delete_bitmap_rowsets) {
  Branch (411:26): [True: 0, False: 0]
412
0
                if (is_incremental_clone) {
  Branch (412:21): [True: 0, False: 0]
413
0
                    calc_bm_status = update_delete_bitmap_without_lock(self, rs);
414
0
                } else {
415
0
                    calc_bm_status = update_delete_bitmap_without_lock(
416
0
                            self, rs, &base_rowsets_for_full_clone);
417
0
                    base_rowsets_for_full_clone.push_back(rs);
418
0
                }
419
0
                if (!calc_bm_status.ok()) {
  Branch (419:21): [True: 0, False: 0]
420
0
                    LOG(WARNING) << "fail to update_delete_bitmap_without_lock, res: "
421
0
                                 << calc_bm_status;
422
0
                    break;
423
0
                }
424
0
            }
425
0
        }
426
0
        break; // while (keys_type() == UNIQUE_KEYS && enable_unique_key_merge_on_write())
427
0
    }
428
429
0
    DBUG_EXECUTE_IF("Tablet.revise_tablet_meta_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
    }
430
0
        auto ptablet_id = dp->param("tablet_id", 0);
431
0
        if (tablet_id() == ptablet_id) {
432
0
            LOG(INFO) << "injected revies_tablet_meta failure for tabelt: " << ptablet_id;
433
0
            calc_bm_status = Status::InternalError("fault injection error");
434
0
        }
435
0
    });
436
437
    // error handling
438
0
    if (!calc_bm_status.ok()) {
  Branch (438:9): [True: 0, False: 0]
439
0
        if (is_incremental_clone) {
  Branch (439:13): [True: 0, False: 0]
440
0
            RETURN_IF_ERROR(delete_rowsets(to_add, false));
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]
441
0
            LOG(WARNING) << "incremental clone on tablet: " << tablet_id() << " failed due to "
442
0
                         << calc_bm_status.msg() << ", revert " << to_add.size()
443
0
                         << " rowsets added before.";
444
0
        } else {
445
0
            LOG(WARNING) << "full clone on tablet: " << tablet_id() << " failed due to "
446
0
                         << calc_bm_status.msg() << ", will not update tablet meta.";
447
0
        }
448
0
        return calc_bm_status;
449
0
    }
450
451
    // full clone, calculate delete bitmap succeeded, update rowset
452
0
    if (!is_incremental_clone) {
  Branch (452:9): [True: 0, False: 0]
453
0
        RETURN_IF_ERROR(delete_rowsets(to_delete, false));
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]
454
0
        add_rowsets(to_add);
455
        // reconstruct from tablet meta
456
0
        _timestamped_version_tracker.construct_versioned_tracker(_tablet_meta->all_rs_metas());
457
458
        // check the rowsets used for delete bitmap calculation is equal to the rowsets
459
        // that we can capture by version
460
0
        if (keys_type() == UNIQUE_KEYS && enable_unique_key_merge_on_write()) {
  Branch (460:13): [True: 0, False: 0]
  Branch (460:43): [True: 0, False: 0]
461
0
            Version full_version = Version(0, max_version_unlocked());
462
0
            auto ret = capture_consistent_rowsets_unlocked(full_version, CaptureRowsetOps {});
463
0
            DCHECK(ret) << ret.error();
464
0
            DCHECK_EQ(base_rowsets_for_full_clone.size(), ret->rowsets.size());
465
466
0
            if (ret && base_rowsets_for_full_clone.size() != ret->rowsets.size()) [[unlikely]] {
  Branch (466:17): [True: 0, False: 0]
  Branch (466:24): [True: 0, False: 0]
467
0
                LOG(WARNING) << "full clone succeeded, but the count("
468
0
                             << base_rowsets_for_full_clone.size()
469
0
                             << ") of base rowsets used for delete bitmap calculation is not match "
470
0
                                "expect count("
471
0
                             << ret->rowsets.size() << ") we capture from tablet meta";
472
0
            }
473
0
        }
474
0
    }
475
476
    // clear stale rowset
477
0
    for (auto& [v, rs] : _stale_rs_version_map) {
  Branch (477:24): [True: 0, False: 0]
478
0
        _engine.add_unused_rowset(rs);
479
0
    }
480
0
    _stale_rs_version_map.clear();
481
0
    _tablet_meta->clear_stale_rowset();
482
0
    save_meta();
483
484
0
    LOG(INFO) << "finish to revise tablet. tablet_id=" << tablet_id();
485
0
    return Status::OK();
486
0
}
487
488
423
Status Tablet::add_rowset(RowsetSharedPtr rowset) {
489
423
    DCHECK(rowset != nullptr);
490
423
    std::lock_guard<std::shared_mutex> wrlock(_meta_lock);
491
423
    SCOPED_SIMPLE_TRACE_IF_TIMEOUT(TRACE_TABLET_LOCK_THRESHOLD);
Line
Count
Source
31
423
    SCOPED_SIMPLE_TRACE_TO_STREAM_IF_TIMEOUT(timeout, LOG(WARNING))
Line
Count
Source
41
423
    using namespace std::chrono_literals;                                               \
42
423
    auto VARNAME_LINENUM(scoped_simple_trace) = doris::MonotonicMicros();               \
43
423
    SCOPED_CLEANUP({                                                                    \
Line
Count
Source
34
423
    auto VARNAME_LINENUM(scoped_cleanup) = MakeScopedCleanup([&] { func_body });
44
423
        auto VARNAME_LINENUM(timeout_us) =                                              \
45
423
                std::chrono::duration_cast<std::chrono::microseconds>(timeout).count(); \
46
423
        auto VARNAME_LINENUM(cost_us) =                                                 \
47
423
                doris::MonotonicMicros() - VARNAME_LINENUM(scoped_simple_trace);        \
48
423
        if (VARNAME_LINENUM(cost_us) >= VARNAME_LINENUM(timeout_us)) {                  \
49
423
            stream << "Simple trace cost(us): " << VARNAME_LINENUM(cost_us);            \
50
423
        }                                                                               \
51
423
    })
492
    // If the rowset already exist, just return directly.  The rowset_id is an unique-id,
493
    // we can use it to check this situation.
494
423
    if (_contains_rowset(rowset->rowset_id())) {
  Branch (494:9): [True: 0, False: 423]
495
0
        return Status::OK();
496
0
    }
497
    // Otherwise, the version should be not contained in any existing rowset.
498
423
    RETURN_IF_ERROR(_contains_version(rowset->version()));
Line
Count
Source
637
423
    do {                                \
638
423
        Status _status_ = (stmt);       \
639
423
        if (UNLIKELY(!_status_.ok())) { \
Line
Count
Source
36
423
#define UNLIKELY(expr) __builtin_expect(!!(expr), 0)
  Branch (36:24): [True: 0, False: 423]
640
0
            return _status_;            \
641
0
        }                               \
642
423
    } while (false)
  Branch (642:14): [Folded - Ignored]
499
500
423
    RETURN_IF_ERROR(_tablet_meta->add_rs_meta(rowset->rowset_meta()));
Line
Count
Source
637
423
    do {                                \
638
423
        Status _status_ = (stmt);       \
639
423
        if (UNLIKELY(!_status_.ok())) { \
Line
Count
Source
36
423
#define UNLIKELY(expr) __builtin_expect(!!(expr), 0)
  Branch (36:24): [True: 0, False: 423]
640
0
            return _status_;            \
641
0
        }                               \
642
423
    } while (false)
  Branch (642:14): [Folded - Ignored]
501
423
    _rs_version_map[rowset->version()] = rowset;
502
423
    _timestamped_version_tracker.add_version(rowset->version());
503
504
423
    std::vector<RowsetSharedPtr> rowsets_to_delete;
505
    // yiguolei: temp code, should remove the rowset contains by this rowset
506
    // but it should be removed in multi path version
507
561
    for (auto& it : _rs_version_map) {
  Branch (507:19): [True: 561, False: 423]
508
561
        if (rowset->version().contains(it.first) && rowset->version() != it.first) {
  Branch (508:13): [True: 423, False: 138]
  Branch (508:13): [True: 0, False: 561]
  Branch (508:53): [True: 0, False: 423]
509
0
            CHECK(it.second != nullptr)
510
0
                    << "there exist a version=" << it.first
511
0
                    << " contains the input rs with version=" << rowset->version()
512
0
                    << ", but the related rs is null";
513
0
            rowsets_to_delete.push_back(it.second);
514
0
        }
515
561
    }
516
423
    std::vector<RowsetSharedPtr> empty_vec;
517
423
    RETURN_IF_ERROR(modify_rowsets(empty_vec, rowsets_to_delete));
Line
Count
Source
637
423
    do {                                \
638
423
        Status _status_ = (stmt);       \
639
423
        if (UNLIKELY(!_status_.ok())) { \
Line
Count
Source
36
423
#define UNLIKELY(expr) __builtin_expect(!!(expr), 0)
  Branch (36:24): [True: 0, False: 423]
640
0
            return _status_;            \
641
0
        }                               \
642
423
    } while (false)
  Branch (642:14): [Folded - Ignored]
518
423
    ++_newly_created_rowset_num;
519
423
    return Status::OK();
520
423
}
521
522
0
bool Tablet::rowset_exists_unlocked(const RowsetSharedPtr& rowset) {
523
0
    if (auto it = _rs_version_map.find(rowset->version()); it == _rs_version_map.end()) {
  Branch (523:60): [True: 0, False: 0]
524
0
        return false;
525
0
    } else if (rowset->rowset_id() != it->second->rowset_id()) {
  Branch (525:16): [True: 0, False: 0]
526
0
        return false;
527
0
    }
528
0
    return true;
529
0
}
530
531
Status Tablet::modify_rowsets(std::vector<RowsetSharedPtr>& to_add,
532
437
                              std::vector<RowsetSharedPtr>& to_delete, bool check_delete) {
533
    // the compaction process allow to compact the single version, eg: version[4-4].
534
    // this kind of "single version compaction" has same "input version" and "output version".
535
    // which means "to_add->version()" equals to "to_delete->version()".
536
    // So we should delete the "to_delete" before adding the "to_add",
537
    // otherwise, the "to_add" will be deleted from _rs_version_map, eventually.
538
    //
539
    // And if the version of "to_add" and "to_delete" are exactly same. eg:
540
    // to_add:      [7-7]
541
    // to_delete:   [7-7]
542
    // In this case, we no longer need to add the rowset in "to_delete" to
543
    // _stale_rs_version_map, but can delete it directly.
544
545
437
    if (to_add.empty() && to_delete.empty()) {
  Branch (545:9): [True: 423, False: 14]
  Branch (545:27): [True: 423, False: 0]
546
423
        return Status::OK();
547
423
    }
548
549
14
    if (check_delete) {
  Branch (549:9): [True: 13, False: 1]
550
13
        for (auto&& rs : to_delete) {
  Branch (550:24): [True: 13, False: 13]
551
13
            if (auto it = _rs_version_map.find(rs->version()); it == _rs_version_map.end()) {
  Branch (551:64): [True: 0, False: 13]
552
0
                return Status::Error<DELETE_VERSION_ERROR>(
553
0
                        "try to delete not exist version {} from {}", rs->version().to_string(),
554
0
                        tablet_id());
555
13
            } else if (rs->rowset_id() != it->second->rowset_id()) {
  Branch (555:24): [True: 0, False: 13]
556
0
                return Status::Error<DELETE_VERSION_ERROR>(
557
0
                        "try to delete version {} from {}, but rowset id changed, delete rowset id "
558
0
                        "is {}, exists rowsetid is {}",
559
0
                        rs->version().to_string(), tablet_id(), rs->rowset_id().to_string(),
560
0
                        it->second->rowset_id().to_string());
561
0
            }
562
13
        }
563
13
    }
564
565
14
    bool same_version = true;
566
14
    std::sort(to_add.begin(), to_add.end(), Rowset::comparator);
567
14
    std::sort(to_delete.begin(), to_delete.end(), Rowset::comparator);
568
14
    if (to_add.size() == to_delete.size()) {
  Branch (568:9): [True: 13, False: 1]
569
26
        for (int i = 0; i < to_add.size(); ++i) {
  Branch (569:25): [True: 13, False: 13]
570
13
            if (to_add[i]->version() != to_delete[i]->version()) {
  Branch (570:17): [True: 0, False: 13]
571
0
                same_version = false;
572
0
                break;
573
0
            }
574
13
        }
575
13
    } else {
576
1
        same_version = false;
577
1
    }
578
579
14
    std::vector<RowsetMetaSharedPtr> rs_metas_to_delete;
580
14
    int64_t now = ::time(nullptr);
581
14
    for (auto& rs : to_delete) {
  Branch (581:19): [True: 13, False: 14]
582
13
        rs_metas_to_delete.push_back(rs->rowset_meta());
583
13
        _rs_version_map.erase(rs->version());
584
585
13
        if (!same_version) {
  Branch (585:13): [True: 0, False: 13]
586
0
            rs->rowset_meta()->set_stale_at(now);
587
            // put compaction rowsets in _stale_rs_version_map.
588
0
            _stale_rs_version_map[rs->version()] = rs;
589
0
        }
590
13
    }
591
592
14
    std::vector<RowsetMetaSharedPtr> rs_metas_to_add;
593
14
    for (auto& rs : to_add) {
  Branch (593:19): [True: 14, False: 14]
594
14
        rs_metas_to_add.push_back(rs->rowset_meta());
595
14
        _rs_version_map[rs->version()] = rs;
596
597
14
        if (!same_version) {
  Branch (597:13): [True: 1, False: 13]
598
            // If version are same, then _timestamped_version_tracker
599
            // already has this version, no need to add again.
600
1
            _timestamped_version_tracker.add_version(rs->version());
601
1
        }
602
14
        ++_newly_created_rowset_num;
603
14
    }
604
605
14
    _tablet_meta->modify_rs_metas(rs_metas_to_add, rs_metas_to_delete, same_version);
606
607
14
    if (!same_version) {
  Branch (607:9): [True: 1, False: 13]
608
        // add rs_metas_to_delete to tracker
609
1
        _timestamped_version_tracker.add_stale_path_version(rs_metas_to_delete);
610
13
    } else {
611
        // delete rowset in "to_delete" directly
612
13
        for (auto& rs : to_delete) {
  Branch (612:23): [True: 13, False: 13]
613
13
            LOG(INFO) << "add unused rowset " << rs->rowset_id() << " because of same version";
614
13
            if (rs->is_local()) {
  Branch (614:17): [True: 13, False: 0]
615
13
                _engine.add_unused_rowset(rs);
616
13
            }
617
13
        }
618
13
    }
619
14
    return Status::OK();
620
14
}
621
622
5
void Tablet::add_rowsets(const std::vector<RowsetSharedPtr>& to_add) {
623
5
    if (to_add.empty()) {
  Branch (623:9): [True: 0, False: 5]
624
0
        return;
625
0
    }
626
5
    std::vector<RowsetMetaSharedPtr> rs_metas;
627
5
    rs_metas.reserve(to_add.size());
628
5
    for (auto& rs : to_add) {
  Branch (628:19): [True: 5, False: 5]
629
5
        _rs_version_map.emplace(rs->version(), rs);
630
5
        _timestamped_version_tracker.add_version(rs->version());
631
5
        rs_metas.push_back(rs->rowset_meta());
632
5
    }
633
5
    _tablet_meta->modify_rs_metas(rs_metas, {});
634
5
}
635
636
5
Status Tablet::delete_rowsets(const std::vector<RowsetSharedPtr>& to_delete, bool move_to_stale) {
637
5
    if (to_delete.empty()) {
  Branch (637:9): [True: 0, False: 5]
638
0
        return Status::OK();
639
0
    }
640
5
    std::vector<RowsetMetaSharedPtr> rs_metas;
641
5
    rs_metas.reserve(to_delete.size());
642
5
    int64_t now = ::time(nullptr);
643
5
    for (const auto& rs : to_delete) {
  Branch (643:25): [True: 5, False: 5]
644
5
        if (move_to_stale) {
  Branch (644:13): [True: 0, False: 5]
645
0
            rs->rowset_meta()->set_stale_at(now);
646
0
        }
647
5
        rs_metas.push_back(rs->rowset_meta());
648
5
        _rs_version_map.erase(rs->version());
649
5
    }
650
5
    _tablet_meta->modify_rs_metas({}, rs_metas, !move_to_stale);
651
5
    if (move_to_stale) {
  Branch (651:9): [True: 0, False: 5]
652
0
        for (const auto& rs : to_delete) {
  Branch (652:29): [True: 0, False: 0]
653
0
            _stale_rs_version_map[rs->version()] = rs;
654
0
        }
655
0
        _timestamped_version_tracker.add_stale_path_version(rs_metas);
656
5
    } else {
657
5
        for (const auto& rs : to_delete) {
  Branch (657:29): [True: 5, False: 5]
658
5
            _timestamped_version_tracker.delete_version(rs->version());
659
5
            if (rs->is_local()) {
  Branch (659:17): [True: 5, False: 0]
660
5
                _engine.add_unused_rowset(rs);
661
5
                RETURN_IF_ERROR(RowsetMetaManager::remove(_data_dir->get_meta(), tablet_uid(),
Line
Count
Source
637
5
    do {                                \
638
5
        Status _status_ = (stmt);       \
639
5
        if (UNLIKELY(!_status_.ok())) { \
Line
Count
Source
36
5
#define UNLIKELY(expr) __builtin_expect(!!(expr), 0)
  Branch (36:24): [True: 0, False: 5]
640
0
            return _status_;            \
641
0
        }                               \
642
5
    } while (false)
  Branch (642:14): [Folded - Ignored]
662
5
                                                          rs->rowset_meta()->rowset_id()));
663
5
            }
664
5
        }
665
5
    }
666
5
    return Status::OK();
667
5
}
668
669
0
RowsetSharedPtr Tablet::_rowset_with_largest_size() {
670
0
    RowsetSharedPtr largest_rowset = nullptr;
671
0
    for (auto& it : _rs_version_map) {
  Branch (671:19): [True: 0, False: 0]
672
0
        if (it.second->empty() || it.second->zero_num_rows()) {
  Branch (672:13): [True: 0, False: 0]
  Branch (672:35): [True: 0, False: 0]
673
0
            continue;
674
0
        }
675
0
        if (largest_rowset == nullptr || it.second->rowset_meta()->index_disk_size() >
  Branch (675:13): [True: 0, False: 0]
  Branch (675:42): [True: 0, False: 0]
676
0
                                                 largest_rowset->rowset_meta()->index_disk_size()) {
677
0
            largest_rowset = it.second;
678
0
        }
679
0
    }
680
681
0
    return largest_rowset;
682
0
}
683
684
// add inc rowset should not persist tablet meta, because it will be persisted when publish txn.
685
10.5k
Status Tablet::add_inc_rowset(const RowsetSharedPtr& rowset) {
686
10.5k
    DCHECK(rowset != nullptr);
687
10.5k
    std::lock_guard<std::shared_mutex> wrlock(_meta_lock);
688
10.5k
    SCOPED_SIMPLE_TRACE_IF_TIMEOUT(TRACE_TABLET_LOCK_THRESHOLD);
Line
Count
Source
31
10.5k
    SCOPED_SIMPLE_TRACE_TO_STREAM_IF_TIMEOUT(timeout, LOG(WARNING))
Line
Count
Source
41
10.5k
    using namespace std::chrono_literals;                                               \
42
10.5k
    auto VARNAME_LINENUM(scoped_simple_trace) = doris::MonotonicMicros();               \
43
10.5k
    SCOPED_CLEANUP({                                                                    \
Line
Count
Source
34
10.5k
    auto VARNAME_LINENUM(scoped_cleanup) = MakeScopedCleanup([&] { func_body });
44
10.5k
        auto VARNAME_LINENUM(timeout_us) =                                              \
45
10.5k
                std::chrono::duration_cast<std::chrono::microseconds>(timeout).count(); \
46
10.5k
        auto VARNAME_LINENUM(cost_us) =                                                 \
47
10.5k
                doris::MonotonicMicros() - VARNAME_LINENUM(scoped_simple_trace);        \
48
10.5k
        if (VARNAME_LINENUM(cost_us) >= VARNAME_LINENUM(timeout_us)) {                  \
49
10.5k
            stream << "Simple trace cost(us): " << VARNAME_LINENUM(cost_us);            \
50
10.5k
        }                                                                               \
51
10.5k
    })
689
10.5k
    if (_contains_rowset(rowset->rowset_id())) {
  Branch (689:9): [True: 0, False: 10.5k]
690
0
        return Status::OK();
691
0
    }
692
10.5k
    RETURN_IF_ERROR(_contains_version(rowset->version()));
Line
Count
Source
637
10.5k
    do {                                \
638
10.5k
        Status _status_ = (stmt);       \
639
10.5k
        if (UNLIKELY(!_status_.ok())) { \
Line
Count
Source
36
10.5k
#define UNLIKELY(expr) __builtin_expect(!!(expr), 0)
  Branch (36:24): [True: 0, False: 10.5k]
640
0
            return _status_;            \
641
0
        }                               \
642
10.5k
    } while (false)
  Branch (642:14): [Folded - Ignored]
693
694
10.5k
    RETURN_IF_ERROR(_tablet_meta->add_rs_meta(rowset->rowset_meta()));
Line
Count
Source
637
10.5k
    do {                                \
638
10.5k
        Status _status_ = (stmt);       \
639
10.5k
        if (UNLIKELY(!_status_.ok())) { \
Line
Count
Source
36
10.5k
#define UNLIKELY(expr) __builtin_expect(!!(expr), 0)
  Branch (36:24): [True: 0, False: 10.5k]
640
0
            return _status_;            \
641
0
        }                               \
642
10.5k
    } while (false)
  Branch (642:14): [Folded - Ignored]
695
10.5k
    _rs_version_map[rowset->version()] = rowset;
696
697
10.5k
    _timestamped_version_tracker.add_version(rowset->version());
698
699
10.5k
    ++_newly_created_rowset_num;
700
10.5k
    return Status::OK();
701
10.5k
}
702
703
8
void Tablet::_delete_stale_rowset_by_version(const Version& version) {
704
8
    RowsetMetaSharedPtr rowset_meta = _tablet_meta->acquire_stale_rs_meta_by_version(version);
705
8
    if (rowset_meta == nullptr) {
  Branch (705:9): [True: 8, False: 0]
706
8
        return;
707
8
    }
708
0
    _tablet_meta->delete_stale_rs_meta_by_version(version);
709
0
    VLOG_NOTICE << "delete stale rowset. tablet=" << tablet_id() << ", version=" << version;
Line
Count
Source
42
0
#define VLOG_NOTICE VLOG(3)
710
0
}
711
712
1
void Tablet::delete_expired_stale_rowset() {
713
1
    if (config::enable_mow_verbose_log) {
  Branch (713:9): [True: 0, False: 1]
714
0
        LOG_INFO("begin delete_expired_stale_rowset for tablet={}", tablet_id());
Line
Count
Source
118
0
#define LOG_INFO TaggableLogger(__FILE__, __LINE__, google::GLOG_INFO)
715
0
    }
716
1
    int64_t now = UnixSeconds();
717
1
    std::vector<std::pair<Version, std::vector<RowsetId>>> deleted_stale_rowsets;
718
    // hold write lock while processing stable rowset
719
1
    {
720
1
        std::lock_guard<std::shared_mutex> wrlock(_meta_lock);
721
1
        SCOPED_SIMPLE_TRACE_IF_TIMEOUT(TRACE_TABLET_LOCK_THRESHOLD);
Line
Count
Source
31
1
    SCOPED_SIMPLE_TRACE_TO_STREAM_IF_TIMEOUT(timeout, LOG(WARNING))
Line
Count
Source
41
1
    using namespace std::chrono_literals;                                               \
42
1
    auto VARNAME_LINENUM(scoped_simple_trace) = doris::MonotonicMicros();               \
43
1
    SCOPED_CLEANUP({                                                                    \
Line
Count
Source
34
1
    auto VARNAME_LINENUM(scoped_cleanup) = MakeScopedCleanup([&] { func_body });
44
1
        auto VARNAME_LINENUM(timeout_us) =                                              \
45
1
                std::chrono::duration_cast<std::chrono::microseconds>(timeout).count(); \
46
1
        auto VARNAME_LINENUM(cost_us) =                                                 \
47
1
                doris::MonotonicMicros() - VARNAME_LINENUM(scoped_simple_trace);        \
48
1
        if (VARNAME_LINENUM(cost_us) >= VARNAME_LINENUM(timeout_us)) {                  \
49
1
            stream << "Simple trace cost(us): " << VARNAME_LINENUM(cost_us);            \
50
1
        }                                                                               \
51
1
    })
722
        // Compute the end time to delete rowsets, when a expired rowset createtime less then this time, it will be deleted.
723
1
        double expired_stale_sweep_endtime =
724
1
                ::difftime(now, config::tablet_rowset_stale_sweep_time_sec);
725
1
        if (config::tablet_rowset_stale_sweep_by_size) {
  Branch (725:13): [True: 0, False: 1]
726
0
            expired_stale_sweep_endtime = now;
727
0
        }
728
729
1
        std::vector<int64_t> path_id_vec;
730
        // capture the path version to delete
731
1
        _timestamped_version_tracker.capture_expired_paths(
732
1
                static_cast<int64_t>(expired_stale_sweep_endtime), &path_id_vec);
733
734
1
        if (path_id_vec.empty()) {
  Branch (734:13): [True: 0, False: 1]
735
0
            return;
736
0
        }
737
738
1
        const RowsetSharedPtr lastest_delta = get_rowset_with_max_version();
739
1
        if (lastest_delta == nullptr) {
  Branch (739:13): [True: 0, False: 1]
740
0
            LOG(WARNING) << "lastest_delta is null " << tablet_id();
741
0
            return;
742
0
        }
743
744
        // fetch missing version before delete
745
1
        Versions missed_versions = get_missed_versions_unlocked(lastest_delta->end_version());
746
1
        if (!missed_versions.empty()) {
  Branch (746:13): [True: 0, False: 1]
747
0
            LOG(WARNING) << "tablet:" << tablet_id()
748
0
                         << ", missed version for version:" << lastest_delta->end_version();
749
0
            _print_missed_versions(missed_versions);
750
0
            return;
751
0
        }
752
753
        // do check consistent operation
754
1
        auto path_id_iter = path_id_vec.begin();
755
756
1
        std::map<int64_t, PathVersionListSharedPtr> stale_version_path_map;
757
5
        while (path_id_iter != path_id_vec.end()) {
  Branch (757:16): [True: 4, False: 1]
758
4
            PathVersionListSharedPtr version_path =
759
4
                    _timestamped_version_tracker.fetch_and_delete_path_by_id(*path_id_iter);
760
761
4
            Version test_version = Version(0, lastest_delta->end_version());
762
4
            stale_version_path_map[*path_id_iter] = version_path;
763
764
4
            auto ret = capture_consistent_versions_unlocked(test_version, {});
765
            // 1. When there is no consistent versions, we must reconstruct the tracker.
766
4
            if (!ret) {
  Branch (766:17): [True: 0, False: 4]
767
                // 2. fetch missing version after delete
768
0
                Versions after_missed_versions =
769
0
                        get_missed_versions_unlocked(lastest_delta->end_version());
770
771
                // 2.1 check whether missed_versions and after_missed_versions are the same.
772
                // when they are the same, it means we can delete the path securely.
773
0
                bool is_missing = missed_versions.size() != after_missed_versions.size();
774
775
0
                if (!is_missing) {
  Branch (775:21): [True: 0, False: 0]
776
0
                    for (int ver_index = 0; ver_index < missed_versions.size(); ver_index++) {
  Branch (776:45): [True: 0, False: 0]
777
0
                        if (missed_versions[ver_index] != after_missed_versions[ver_index]) {
  Branch (777:29): [True: 0, False: 0]
778
0
                            is_missing = true;
779
0
                            break;
780
0
                        }
781
0
                    }
782
0
                }
783
784
0
                if (is_missing) {
  Branch (784:21): [True: 0, False: 0]
785
0
                    LOG(WARNING) << "The consistent version check fails, there are bugs. "
786
0
                                 << "Reconstruct the tracker to recover versions in tablet="
787
0
                                 << tablet_id();
788
789
                    // 3. try to recover
790
0
                    _timestamped_version_tracker.recover_versioned_tracker(stale_version_path_map);
791
792
                    // 4. double check the consistent versions
793
                    // fetch missing version after recover
794
0
                    Versions recover_missed_versions =
795
0
                            get_missed_versions_unlocked(lastest_delta->end_version());
796
797
                    // 4.1 check whether missed_versions and recover_missed_versions are the same.
798
                    // when they are the same, it means we recover successfully.
799
0
                    bool is_recover_missing =
800
0
                            missed_versions.size() != recover_missed_versions.size();
801
802
0
                    if (!is_recover_missing) {
  Branch (802:25): [True: 0, False: 0]
803
0
                        for (int ver_index = 0; ver_index < missed_versions.size(); ver_index++) {
  Branch (803:49): [True: 0, False: 0]
804
0
                            if (missed_versions[ver_index] != recover_missed_versions[ver_index]) {
  Branch (804:33): [True: 0, False: 0]
805
0
                                is_recover_missing = true;
806
0
                                break;
807
0
                            }
808
0
                        }
809
0
                    }
810
811
                    // 5. check recover fail, version is mission
812
0
                    if (is_recover_missing) {
  Branch (812:25): [True: 0, False: 0]
813
0
                        if (!config::ignore_rowset_stale_unconsistent_delete) {
  Branch (813:29): [True: 0, False: 0]
814
0
                            LOG(FATAL)
815
0
                                    << "rowset stale unconsistent delete. tablet= " << tablet_id();
816
0
                        } else {
817
0
                            LOG(WARNING)
818
0
                                    << "rowset stale unconsistent delete. tablet= " << tablet_id();
819
0
                        }
820
0
                    }
821
0
                }
822
0
                return;
823
0
            }
824
4
            path_id_iter++;
825
4
        }
826
827
1
        auto old_size = _stale_rs_version_map.size();
828
1
        auto old_meta_size = _tablet_meta->all_stale_rs_metas().size();
829
830
        // do delete operation
831
1
        auto to_delete_iter = stale_version_path_map.begin();
832
5
        while (to_delete_iter != stale_version_path_map.end()) {
  Branch (832:16): [True: 4, False: 1]
833
4
            std::vector<TimestampedVersionSharedPtr>& to_delete_version =
834
4
                    to_delete_iter->second->timestamped_versions();
835
4
            int64_t start_version = -1;
836
4
            int64_t end_version = -1;
837
4
            std::vector<RowsetId> remove_rowset_ids;
838
8
            for (auto& timestampedVersion : to_delete_version) {
  Branch (838:43): [True: 8, False: 4]
839
8
                auto it = _stale_rs_version_map.find(timestampedVersion->version());
840
8
                if (it != _stale_rs_version_map.end()) {
  Branch (840:21): [True: 0, False: 8]
841
0
                    it->second->clear_cache();
842
                    // delete rowset
843
0
                    if (it->second->is_local()) {
  Branch (843:25): [True: 0, False: 0]
844
0
                        _engine.add_unused_rowset(it->second);
845
0
                        if (keys_type() == UNIQUE_KEYS && enable_unique_key_merge_on_write()) {
  Branch (845:29): [True: 0, False: 0]
  Branch (845:59): [True: 0, False: 0]
846
                            // mow does not support cold data in object storage
847
0
                            remove_rowset_ids.emplace_back(it->second->rowset_id());
848
0
                        }
849
0
                    }
850
0
                    _stale_rs_version_map.erase(it);
851
0
                    VLOG_NOTICE << "delete stale rowset tablet=" << tablet_id() << " version["
Line
Count
Source
42
0
#define VLOG_NOTICE VLOG(3)
852
0
                                << timestampedVersion->version().first << ","
853
0
                                << timestampedVersion->version().second
854
0
                                << "] move to unused_rowset success " << std::fixed
855
0
                                << expired_stale_sweep_endtime;
856
8
                } else {
857
8
                    LOG(WARNING) << "delete stale rowset tablet=" << tablet_id() << " version["
858
8
                                 << timestampedVersion->version().first << ","
859
8
                                 << timestampedVersion->version().second
860
8
                                 << "] not find in stale rs version map";
861
8
                }
862
8
                if (start_version < 0) {
  Branch (862:21): [True: 4, False: 4]
863
4
                    start_version = timestampedVersion->version().first;
864
4
                }
865
8
                end_version = timestampedVersion->version().second;
866
8
                _delete_stale_rowset_by_version(timestampedVersion->version());
867
8
            }
868
4
            Version version(start_version, end_version);
869
4
            to_delete_iter++;
870
4
            if (!remove_rowset_ids.empty()) {
  Branch (870:17): [True: 0, False: 4]
871
0
                deleted_stale_rowsets.emplace_back(version, remove_rowset_ids);
872
0
            }
873
4
        }
874
875
1
        bool reconstructed = _reconstruct_version_tracker_if_necessary();
876
877
1
        VLOG_NOTICE << "delete stale rowset _stale_rs_version_map tablet=" << tablet_id()
Line
Count
Source
42
0
#define VLOG_NOTICE VLOG(3)
878
0
                    << " current_size=" << _stale_rs_version_map.size() << " old_size=" << old_size
879
0
                    << " current_meta_size=" << _tablet_meta->all_stale_rs_metas().size()
880
0
                    << " old_meta_size=" << old_meta_size << " sweep endtime " << std::fixed
881
0
                    << expired_stale_sweep_endtime << ", reconstructed=" << reconstructed;
882
1
    }
883
1
    if (config::enable_agg_and_remove_pre_rowsets_delete_bitmap && !deleted_stale_rowsets.empty()) {
  Branch (883:9): [True: 1, False: 0]
  Branch (883:68): [True: 0, False: 1]
884
        // agg delete bitmap for pre rowsets; record unused delete bitmap key ranges
885
0
        OlapStopWatch watch;
886
0
        for (const auto& [version, remove_rowset_ids] : deleted_stale_rowsets) {
  Branch (886:55): [True: 0, False: 0]
887
            // agg delete bitmap for pre rowset
888
0
            DeleteBitmapKeyRanges remove_delete_bitmap_key_ranges;
889
0
            agg_delete_bitmap_for_stale_rowsets(version, remove_delete_bitmap_key_ranges);
890
            // add remove delete bitmap
891
0
            if (!remove_delete_bitmap_key_ranges.empty()) {
  Branch (891:17): [True: 0, False: 0]
892
0
                _engine.add_unused_delete_bitmap_key_ranges(tablet_id(), remove_rowset_ids,
893
0
                                                            remove_delete_bitmap_key_ranges);
894
0
            }
895
0
        }
896
0
        LOG(INFO) << "agg pre rowsets delete bitmap. tablet_id=" << tablet_id()
897
0
                  << ", size=" << deleted_stale_rowsets.size()
898
0
                  << ", cost(us)=" << watch.get_elapse_time_us();
899
0
    }
900
#ifndef BE_TEST
901
    {
902
        std::shared_lock<std::shared_mutex> rlock(_meta_lock);
903
        save_meta();
904
    }
905
#endif
906
1
    if (config::enable_mow_verbose_log) {
  Branch (906:9): [True: 0, False: 1]
907
0
        LOG_INFO("finish delete_expired_stale_rowset for tablet={}", tablet_id());
Line
Count
Source
118
0
#define LOG_INFO TaggableLogger(__FILE__, __LINE__, google::GLOG_INFO)
908
0
    }
909
1
    DBUG_EXECUTE_IF("Tablet.delete_expired_stale_rowset.start_delete_unused_rowset",
Line
Count
Source
37
1
    if (UNLIKELY(config::enable_debug_points)) {                              \
Line
Count
Source
36
1
#define UNLIKELY(expr) __builtin_expect(!!(expr), 0)
  Branch (36:24): [True: 0, False: 1]
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; }                                                         \
42
0
        }                                                                     \
43
0
    }
910
1
                    { _engine.start_delete_unused_rowset(); });
911
1
}
912
913
0
Status Tablet::check_version_integrity(const Version& version, bool quiet) {
914
0
    std::shared_lock rdlock(_meta_lock);
915
0
    [[maybe_unused]] auto _versions = DORIS_TRY(
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
    });
916
0
            capture_consistent_versions_unlocked(version, CaptureRowsetOps {.quiet = quiet}));
917
0
    return Status::OK();
918
0
}
919
920
28
bool Tablet::exceed_version_limit(int32_t limit) {
921
28
    if (_tablet_meta->version_count() > limit) {
  Branch (921:9): [True: 0, False: 28]
922
0
        exceed_version_limit_counter << 1;
923
0
        return true;
924
0
    }
925
28
    return false;
926
28
}
927
928
// If any rowset contains the specific version, it means the version already exist
929
1
bool Tablet::check_version_exist(const Version& version) const {
930
1
    std::shared_lock rdlock(_meta_lock);
931
3
    for (auto& it : _rs_version_map) {
  Branch (931:19): [True: 3, False: 1]
932
3
        if (it.first.contains(version)) {
  Branch (932:13): [True: 0, False: 3]
933
0
            return true;
934
0
        }
935
3
    }
936
1
    return false;
937
1
}
938
939
// The meta read lock should be held before calling
940
void Tablet::acquire_version_and_rowsets(
941
0
        std::vector<std::pair<Version, RowsetSharedPtr>>* version_rowsets) const {
942
0
    for (const auto& it : _rs_version_map) {
  Branch (942:25): [True: 0, False: 0]
943
0
        version_rowsets->emplace_back(it.first, it.second);
944
0
    }
945
0
}
946
947
Status Tablet::capture_rs_readers(const Version& spec_version, std::vector<RowSetSplits>* rs_splits,
948
2
                                  bool skip_missing_version) {
949
2
    std::shared_lock rlock(_meta_lock);
950
2
    std::vector<Version> version_path;
951
2
    *rs_splits = DORIS_TRY(capture_rs_readers_unlocked(
Line
Count
Source
716
2
    ({                                           \
717
2
        auto&& res = (stmt);                     \
718
2
        using T = std::decay_t<decltype(res)>;   \
719
2
        if (!res.has_value()) [[unlikely]] {     \
  Branch (719:13): [True: 1, False: 1]
720
1
            return std::forward<T>(res).error(); \
721
1
        }                                        \
722
2
        std::forward<T>(res).value();            \
723
1
    });
952
1
            spec_version, CaptureRowsetOps {.skip_missing_versions = skip_missing_version}));
953
1
    return Status::OK();
954
2
}
955
956
2
Versions Tablet::calc_missed_versions(int64_t spec_version, Versions existing_versions) const {
957
2
    DCHECK(spec_version > 0) << "invalid spec_version: " << spec_version;
958
959
    // sort the existing versions in ascending order
960
2
    std::sort(existing_versions.begin(), existing_versions.end(),
961
12
              [](const Version& a, const Version& b) {
962
                  // simple because 2 versions are certainly not overlapping
963
12
                  return a.first < b.first;
964
12
              });
965
966
    // From the first version(=0),  find the missing version until spec_version
967
2
    int64_t last_version = -1;
968
2
    Versions missed_versions;
969
8
    for (const Version& version : existing_versions) {
  Branch (969:33): [True: 8, False: 0]
970
8
        if (version.first > last_version + 1) {
  Branch (970:13): [True: 2, False: 6]
971
4
            for (int64_t i = last_version + 1; i < version.first && i <= spec_version; ++i) {
  Branch (971:48): [True: 2, False: 2]
  Branch (971:69): [True: 2, False: 0]
972
                // Don't merge missed_versions because clone & snapshot use single version.
973
                // For example, if miss 4 ~ 6, clone need [4, 4], [5, 5], [6, 6], but not [4, 6].
974
2
                missed_versions.emplace_back(i, i);
975
2
            }
976
2
        }
977
8
        last_version = version.second;
978
8
        if (last_version >= spec_version) {
  Branch (978:13): [True: 2, False: 6]
979
2
            break;
980
2
        }
981
8
    }
982
2
    for (int64_t i = last_version + 1; i <= spec_version; ++i) {
  Branch (982:40): [True: 0, False: 2]
983
0
        missed_versions.emplace_back(i, i);
984
0
    }
985
986
2
    return missed_versions;
987
2
}
988
989
262
bool Tablet::can_do_compaction(size_t path_hash, CompactionType compaction_type) {
990
262
    if (compaction_type == CompactionType::BASE_COMPACTION && tablet_state() != TABLET_RUNNING) {
  Branch (990:9): [True: 0, False: 262]
  Branch (990:63): [True: 0, False: 0]
991
        // base compaction can only be done for tablet in TABLET_RUNNING state.
992
        // but cumulative compaction can be done for TABLET_NOTREADY, such as tablet under alter process.
993
0
        return false;
994
0
    }
995
996
262
    if (data_dir()->path_hash() != path_hash || !is_used() || !init_succeeded()) {
  Branch (996:9): [True: 0, False: 262]
  Branch (996:49): [True: 0, False: 262]
  Branch (996:63): [True: 0, False: 262]
997
0
        return false;
998
0
    }
999
1000
    // In TABLET_NOTREADY, we keep last 10 versions in new tablet so base tablet max_version
1001
    // not merged in new tablet and then we can do compaction
1002
262
    return tablet_state() == TABLET_RUNNING || tablet_state() == TABLET_NOTREADY;
  Branch (1002:12): [True: 262, False: 0]
  Branch (1002:48): [True: 0, False: 0]
1003
262
}
1004
1005
uint32_t Tablet::calc_compaction_score(
1006
        CompactionType compaction_type,
1007
285
        std::shared_ptr<CumulativeCompactionPolicy> cumulative_compaction_policy) {
1008
    // Need meta lock, because it will iterator "all_rs_metas" of tablet meta.
1009
285
    std::shared_lock rdlock(_meta_lock);
1010
285
    if (compaction_type == CompactionType::CUMULATIVE_COMPACTION) {
  Branch (1010:9): [True: 285, False: 0]
1011
285
        return _calc_cumulative_compaction_score(cumulative_compaction_policy);
1012
285
    } else {
1013
0
        DCHECK_EQ(compaction_type, CompactionType::BASE_COMPACTION);
1014
0
        return _calc_base_compaction_score();
1015
0
    }
1016
285
}
1017
1018
0
uint32_t Tablet::calc_cold_data_compaction_score() const {
1019
0
    uint32_t score = 0;
1020
0
    std::vector<RowsetMetaSharedPtr> cooldowned_rowsets;
1021
0
    int64_t max_delete_version = 0;
1022
0
    {
1023
0
        std::shared_lock rlock(_meta_lock);
1024
0
        for (auto& rs_meta : _tablet_meta->all_rs_metas()) {
  Branch (1024:28): [True: 0, False: 0]
1025
0
            if (!rs_meta->is_local()) {
  Branch (1025:17): [True: 0, False: 0]
1026
0
                cooldowned_rowsets.push_back(rs_meta);
1027
0
                if (rs_meta->has_delete_predicate() &&
  Branch (1027:21): [True: 0, False: 0]
1028
0
                    rs_meta->end_version() > max_delete_version) {
  Branch (1028:21): [True: 0, False: 0]
1029
0
                    max_delete_version = rs_meta->end_version();
1030
0
                }
1031
0
            }
1032
0
        }
1033
0
    }
1034
0
    for (auto& rs_meta : cooldowned_rowsets) {
  Branch (1034:24): [True: 0, False: 0]
1035
0
        if (rs_meta->end_version() < max_delete_version) {
  Branch (1035:13): [True: 0, False: 0]
1036
0
            score += rs_meta->num_segments();
1037
0
        } else {
1038
0
            score += rs_meta->get_compaction_score();
1039
0
        }
1040
0
    }
1041
0
    return (keys_type() != KeysType::DUP_KEYS) ? score * 2 : score;
  Branch (1041:12): [True: 0, False: 0]
1042
0
}
1043
1044
uint32_t Tablet::_calc_cumulative_compaction_score(
1045
285
        std::shared_ptr<CumulativeCompactionPolicy> cumulative_compaction_policy) {
1046
285
    if (cumulative_compaction_policy == nullptr) [[unlikely]] {
  Branch (1046:9): [True: 0, False: 285]
1047
0
        return 0;
1048
0
    }
1049
#ifndef BE_TEST
1050
    if (_cumulative_compaction_policy == nullptr ||
1051
        _cumulative_compaction_policy->name() != cumulative_compaction_policy->name()) {
1052
        _cumulative_compaction_policy = cumulative_compaction_policy;
1053
    }
1054
#endif
1055
285
    DBUG_EXECUTE_IF("Tablet._calc_cumulative_compaction_score.return", {
Line
Count
Source
37
285
    if (UNLIKELY(config::enable_debug_points)) {                              \
Line
Count
Source
36
285
#define UNLIKELY(expr) __builtin_expect(!!(expr), 0)
  Branch (36:24): [True: 0, False: 285]
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; }                                                         \
42
0
        }                                                                     \
43
0
    }
1056
285
        LOG_WARNING("Tablet._calc_cumulative_compaction_score.return")
1057
285
                .tag("tablet id", tablet_id());
1058
285
        return 0;
1059
285
    });
1060
285
    return _cumulative_compaction_policy->calc_cumulative_compaction_score(this);
1061
285
}
1062
1063
0
uint32_t Tablet::_calc_base_compaction_score() const {
1064
0
    uint32_t score = 0;
1065
0
    const int64_t point = cumulative_layer_point();
1066
0
    bool base_rowset_exist = false;
1067
0
    bool has_delete = false;
1068
0
    for (auto& rs_meta : _tablet_meta->all_rs_metas()) {
  Branch (1068:24): [True: 0, False: 0]
1069
0
        if (rs_meta->start_version() == 0) {
  Branch (1069:13): [True: 0, False: 0]
1070
0
            base_rowset_exist = true;
1071
0
        }
1072
0
        if (rs_meta->start_version() >= point || !rs_meta->is_local()) {
  Branch (1072:13): [True: 0, False: 0]
  Branch (1072:50): [True: 0, False: 0]
1073
            // all_rs_metas() is not sorted, so we use _continue_ other than _break_ here.
1074
0
            continue;
1075
0
        }
1076
0
        if (rs_meta->has_delete_predicate()) {
  Branch (1076:13): [True: 0, False: 0]
1077
0
            has_delete = true;
1078
0
        }
1079
0
        score += rs_meta->get_compaction_score();
1080
0
    }
1081
1082
    // In the time series compaction policy, we want the base compaction to be triggered
1083
    // when there are delete versions present.
1084
0
    if (_tablet_meta->compaction_policy() == CUMULATIVE_TIME_SERIES_POLICY) {
  Branch (1084:9): [True: 0, False: 0]
1085
0
        return (base_rowset_exist && has_delete) ? score : 0;
  Branch (1085:17): [True: 0, False: 0]
  Branch (1085:38): [True: 0, False: 0]
1086
0
    }
1087
1088
    // base不存在可能是tablet正在做alter table,先不选它,设score=0
1089
0
    return base_rowset_exist ? score : 0;
  Branch (1089:12): [True: 0, False: 0]
1090
0
}
1091
1092
0
void Tablet::max_continuous_version_from_beginning(Version* version, Version* max_version) {
1093
0
    bool has_version_cross;
1094
0
    std::shared_lock rdlock(_meta_lock);
1095
0
    _max_continuous_version_from_beginning_unlocked(version, max_version, &has_version_cross);
1096
0
}
1097
1098
void Tablet::_max_continuous_version_from_beginning_unlocked(Version* version, Version* max_version,
1099
0
                                                             bool* has_version_cross) const {
1100
0
    std::vector<Version> existing_versions;
1101
0
    *has_version_cross = false;
1102
0
    for (auto& rs : _tablet_meta->all_rs_metas()) {
  Branch (1102:19): [True: 0, False: 0]
1103
0
        existing_versions.emplace_back(rs->version());
1104
0
    }
1105
1106
    // sort the existing versions in ascending order
1107
0
    std::sort(existing_versions.begin(), existing_versions.end(),
1108
0
              [](const Version& left, const Version& right) {
1109
                  // simple because 2 versions are certainly not overlapping
1110
0
                  return left.first < right.first;
1111
0
              });
1112
1113
0
    Version max_continuous_version = {-1, -1};
1114
0
    for (int i = 0; i < existing_versions.size(); ++i) {
  Branch (1114:21): [True: 0, False: 0]
1115
0
        if (existing_versions[i].first > max_continuous_version.second + 1) {
  Branch (1115:13): [True: 0, False: 0]
1116
0
            break;
1117
0
        } else if (existing_versions[i].first <= max_continuous_version.second) {
  Branch (1117:20): [True: 0, False: 0]
1118
0
            *has_version_cross = true;
1119
0
        }
1120
0
        max_continuous_version = existing_versions[i];
1121
0
    }
1122
0
    *version = max_continuous_version;
1123
    // tablet may not has rowset, eg, tablet has just been clear for restore.
1124
0
    if (max_version != nullptr && !existing_versions.empty()) {
  Branch (1124:9): [True: 0, False: 0]
  Branch (1124:35): [True: 0, False: 0]
1125
0
        *max_version = existing_versions.back();
1126
0
    }
1127
0
}
1128
1129
49
void Tablet::calculate_cumulative_point() {
1130
49
    std::lock_guard<std::shared_mutex> wrlock(_meta_lock);
1131
49
    SCOPED_SIMPLE_TRACE_IF_TIMEOUT(TRACE_TABLET_LOCK_THRESHOLD);
Line
Count
Source
31
49
    SCOPED_SIMPLE_TRACE_TO_STREAM_IF_TIMEOUT(timeout, LOG(WARNING))
Line
Count
Source
41
49
    using namespace std::chrono_literals;                                               \
42
49
    auto VARNAME_LINENUM(scoped_simple_trace) = doris::MonotonicMicros();               \
43
49
    SCOPED_CLEANUP({                                                                    \
Line
Count
Source
34
49
    auto VARNAME_LINENUM(scoped_cleanup) = MakeScopedCleanup([&] { func_body });
44
49
        auto VARNAME_LINENUM(timeout_us) =                                              \
45
49
                std::chrono::duration_cast<std::chrono::microseconds>(timeout).count(); \
46
49
        auto VARNAME_LINENUM(cost_us) =                                                 \
47
49
                doris::MonotonicMicros() - VARNAME_LINENUM(scoped_simple_trace);        \
48
49
        if (VARNAME_LINENUM(cost_us) >= VARNAME_LINENUM(timeout_us)) {                  \
49
49
            stream << "Simple trace cost(us): " << VARNAME_LINENUM(cost_us);            \
50
49
        }                                                                               \
51
49
    })
1132
49
    int64_t ret_cumulative_point;
1133
49
    _cumulative_compaction_policy->calculate_cumulative_point(
1134
49
            this, _tablet_meta->all_rs_metas(), _cumulative_point, &ret_cumulative_point);
1135
1136
49
    if (ret_cumulative_point == K_INVALID_CUMULATIVE_POINT) {
  Branch (1136:9): [True: 21, False: 28]
1137
21
        return;
1138
21
    }
1139
28
    set_cumulative_layer_point(ret_cumulative_point);
1140
28
}
1141
1142
// NOTE: only used when create_table, so it is sure that there is no concurrent reader and writer.
1143
0
void Tablet::delete_all_files() {
1144
    // Release resources like memory and disk space.
1145
0
    std::shared_lock rdlock(_meta_lock);
1146
0
    for (auto it : _rs_version_map) {
  Branch (1146:18): [True: 0, False: 0]
1147
0
        static_cast<void>(it.second->remove());
1148
0
    }
1149
0
    _rs_version_map.clear();
1150
1151
0
    for (auto it : _stale_rs_version_map) {
  Branch (1151:18): [True: 0, False: 0]
1152
0
        static_cast<void>(it.second->remove());
1153
0
    }
1154
0
    _stale_rs_version_map.clear();
1155
0
}
1156
1157
0
void Tablet::check_tablet_path_exists() {
1158
0
    if (!tablet_path().empty()) {
  Branch (1158:9): [True: 0, False: 0]
1159
0
        std::error_code ec;
1160
0
        if (std::filesystem::is_directory(tablet_path(), ec)) {
  Branch (1160:13): [True: 0, False: 0]
1161
0
            _is_tablet_path_exists.store(true, std::memory_order_relaxed);
1162
0
        } else if (ec.value() == ENOENT || ec.value() == 0) {
  Branch (1162:20): [True: 0, False: 0]
  Branch (1162:44): [True: 0, False: 0]
1163
0
            _is_tablet_path_exists.store(false, std::memory_order_relaxed);
1164
0
        }
1165
0
    }
1166
0
}
1167
1168
10.9k
Status Tablet::_contains_version(const Version& version) {
1169
    // check if there exist a rowset contains the added rowset
1170
356k
    for (auto& it : _rs_version_map) {
  Branch (1170:19): [True: 356k, False: 10.9k]
1171
356k
        if (it.first.contains(version)) {
  Branch (1171:13): [True: 0, False: 356k]
1172
            // TODO(lingbin): Is this check unnecessary?
1173
            // because the value type is std::shared_ptr, when will it be nullptr?
1174
            // In addition, in this class, there are many places that do not make this judgment
1175
            // when access _rs_version_map's value.
1176
0
            CHECK(it.second != nullptr) << "there exist a version=" << it.first
1177
0
                                        << " contains the input rs with version=" << version
1178
0
                                        << ", but the related rs is null";
1179
0
            return Status::Error<PUSH_VERSION_ALREADY_EXIST>("Tablet push duplicate version {}",
1180
0
                                                             version.to_string());
1181
0
        }
1182
356k
    }
1183
1184
10.9k
    return Status::OK();
1185
10.9k
}
1186
1187
40
std::vector<RowsetSharedPtr> Tablet::pick_candidate_rowsets_to_cumulative_compaction() {
1188
40
    std::vector<RowsetSharedPtr> candidate_rowsets;
1189
40
    if (_cumulative_point == K_INVALID_CUMULATIVE_POINT) {
  Branch (1189:9): [True: 0, False: 40]
1190
0
        return candidate_rowsets;
1191
0
    }
1192
40
    return _pick_visible_rowsets_to_compaction(_cumulative_point,
1193
40
                                               std::numeric_limits<int64_t>::max());
1194
40
}
1195
1196
1
std::vector<RowsetSharedPtr> Tablet::pick_candidate_rowsets_to_base_compaction() {
1197
1
    return _pick_visible_rowsets_to_compaction(std::numeric_limits<int64_t>::min(),
1198
1
                                               _cumulative_point - 1);
1199
1
}
1200
1201
std::vector<RowsetSharedPtr> Tablet::_pick_visible_rowsets_to_compaction(
1202
41
        int64_t min_start_version, int64_t max_start_version) {
1203
41
    auto [visible_version, update_ts] = get_visible_version_and_time();
1204
41
    bool update_time_long = MonotonicMillis() - update_ts >
1205
41
                            config::compaction_keep_invisible_version_timeout_sec * 1000L;
1206
41
    int32_t keep_invisible_version_limit =
1207
41
            update_time_long ? config::compaction_keep_invisible_version_min_count
  Branch (1207:13): [True: 0, False: 41]
1208
41
                             : config::compaction_keep_invisible_version_max_count;
1209
1210
41
    std::vector<RowsetSharedPtr> candidate_rowsets;
1211
41
    {
1212
41
        std::shared_lock rlock(_meta_lock);
1213
715
        for (const auto& [version, rs] : _rs_version_map) {
  Branch (1213:40): [True: 715, False: 41]
1214
715
            int64_t version_start = version.first;
1215
            // rowset is remote or rowset is not in given range
1216
715
            if (!rs->is_local() || version_start < min_start_version ||
  Branch (1216:17): [True: 0, False: 715]
  Branch (1216:36): [True: 26, False: 689]
1217
715
                version_start > max_start_version) {
  Branch (1217:17): [True: 5, False: 684]
1218
31
                continue;
1219
31
            }
1220
1221
            // can compact, met one of the conditions:
1222
            // 1. had been visible;
1223
            // 2. exceeds the limit of keep invisible versions.
1224
684
            int64_t version_end = version.second;
1225
684
            if (version_end <= visible_version ||
  Branch (1225:17): [True: 684, False: 0]
1226
684
                version_end > visible_version + keep_invisible_version_limit) {
  Branch (1226:17): [True: 0, False: 0]
1227
684
                candidate_rowsets.push_back(rs);
1228
684
            }
1229
684
        }
1230
41
    }
1231
41
    std::sort(candidate_rowsets.begin(), candidate_rowsets.end(), Rowset::comparator);
1232
41
    return candidate_rowsets;
1233
41
}
1234
1235
0
std::vector<RowsetSharedPtr> Tablet::pick_candidate_rowsets_to_full_compaction() {
1236
0
    std::vector<RowsetSharedPtr> candidate_rowsets;
1237
0
    traverse_rowsets([&candidate_rowsets](const auto& rs) {
1238
        // Do full compaction on all local rowsets.
1239
0
        if (rs->is_local()) {
  Branch (1239:13): [True: 0, False: 0]
1240
0
            candidate_rowsets.emplace_back(rs);
1241
0
        }
1242
0
    });
1243
0
    std::sort(candidate_rowsets.begin(), candidate_rowsets.end(), Rowset::comparator);
1244
0
    return candidate_rowsets;
1245
0
}
1246
1247
std::vector<RowsetSharedPtr> Tablet::pick_candidate_rowsets_to_build_inverted_index(
1248
18
        const std::set<int64_t>& alter_index_uids, bool is_drop_op) {
1249
18
    std::vector<RowsetSharedPtr> candidate_rowsets;
1250
18
    {
1251
18
        std::shared_lock rlock(_meta_lock);
1252
35
        auto has_alter_inverted_index = [&](RowsetSharedPtr rowset) -> bool {
1253
39
            for (const auto& index_id : alter_index_uids) {
  Branch (1253:39): [True: 39, False: 31]
1254
39
                if (rowset->tablet_schema()->has_inverted_index_with_index_id(index_id)) {
  Branch (1254:21): [True: 4, False: 35]
1255
4
                    return true;
1256
4
                }
1257
39
            }
1258
31
            return false;
1259
35
        };
1260
1261
18
        for (const auto& [version, rs] : _rs_version_map) {
  Branch (1261:40): [True: 18, False: 18]
1262
18
            if (!has_alter_inverted_index(rs) && is_drop_op) {
  Branch (1262:17): [True: 16, False: 2]
  Branch (1262:17): [True: 1, False: 17]
  Branch (1262:50): [True: 1, False: 15]
1263
1
                continue;
1264
1
            }
1265
17
            if (has_alter_inverted_index(rs) && !is_drop_op) {
  Branch (1265:17): [True: 2, False: 15]
  Branch (1265:17): [True: 0, False: 17]
  Branch (1265:49): [True: 0, False: 2]
1266
0
                continue;
1267
0
            }
1268
1269
17
            if (rs->is_local()) {
  Branch (1269:17): [True: 17, False: 0]
1270
17
                candidate_rowsets.push_back(rs);
1271
17
            }
1272
17
        }
1273
18
    }
1274
18
    std::sort(candidate_rowsets.begin(), candidate_rowsets.end(), Rowset::comparator);
1275
18
    return candidate_rowsets;
1276
18
}
1277
1278
41
std::tuple<int64_t, int64_t> Tablet::get_visible_version_and_time() const {
1279
    // some old tablet has bug, its partition_id is 0, fe couldn't update its visible version.
1280
    // so let this tablet's visible version become int64 max.
1281
41
    auto version_info = std::atomic_load_explicit(&_visible_version, std::memory_order_relaxed);
1282
41
    if (version_info != nullptr && partition_id() != 0) {
  Branch (1282:9): [True: 0, False: 41]
  Branch (1282:36): [True: 0, False: 0]
1283
0
        return std::make_tuple(version_info->version.load(std::memory_order_relaxed),
1284
0
                               version_info->update_ts);
1285
41
    } else {
1286
41
        return std::make_tuple(std::numeric_limits<int64_t>::max(),
1287
41
                               std::numeric_limits<int64_t>::max());
1288
41
    }
1289
41
}
1290
1291
// For http compaction action
1292
0
void Tablet::get_compaction_status(std::string* json_result) {
1293
0
    rapidjson::Document root;
1294
0
    root.SetObject();
1295
1296
0
    rapidjson::Document path_arr;
1297
0
    path_arr.SetArray();
1298
1299
0
    std::vector<RowsetSharedPtr> rowsets;
1300
0
    std::vector<RowsetSharedPtr> stale_rowsets;
1301
0
    std::vector<bool> delete_flags;
1302
0
    {
1303
0
        std::shared_lock rdlock(_meta_lock);
1304
0
        rowsets.reserve(_rs_version_map.size());
1305
0
        for (auto& it : _rs_version_map) {
  Branch (1305:23): [True: 0, False: 0]
1306
0
            rowsets.push_back(it.second);
1307
0
        }
1308
0
        std::sort(rowsets.begin(), rowsets.end(), Rowset::comparator);
1309
1310
0
        stale_rowsets.reserve(_stale_rs_version_map.size());
1311
0
        for (auto& it : _stale_rs_version_map) {
  Branch (1311:23): [True: 0, False: 0]
1312
0
            stale_rowsets.push_back(it.second);
1313
0
        }
1314
0
        std::sort(stale_rowsets.begin(), stale_rowsets.end(), Rowset::comparator);
1315
1316
0
        delete_flags.reserve(rowsets.size());
1317
0
        for (auto& rs : rowsets) {
  Branch (1317:23): [True: 0, False: 0]
1318
0
            delete_flags.push_back(rs->rowset_meta()->has_delete_predicate());
1319
0
        }
1320
        // get snapshot version path json_doc
1321
0
        _timestamped_version_tracker.get_stale_version_path_json_doc(path_arr);
1322
0
    }
1323
0
    rapidjson::Value cumulative_policy_type;
1324
0
    std::string policy_type_str = "cumulative compaction policy not initializied";
1325
0
    if (_cumulative_compaction_policy != nullptr) {
  Branch (1325:9): [True: 0, False: 0]
1326
0
        policy_type_str = _cumulative_compaction_policy->name();
1327
0
    }
1328
0
    cumulative_policy_type.SetString(policy_type_str.c_str(), policy_type_str.length(),
1329
0
                                     root.GetAllocator());
1330
0
    root.AddMember("cumulative policy type", cumulative_policy_type, root.GetAllocator());
1331
0
    root.AddMember("cumulative point", _cumulative_point.load(), root.GetAllocator());
1332
0
    rapidjson::Value cumu_value;
1333
0
    std::string format_str = ToStringFromUnixMillis(_last_cumu_compaction_failure_millis.load());
1334
0
    cumu_value.SetString(format_str.c_str(), format_str.length(), root.GetAllocator());
1335
0
    root.AddMember("last cumulative failure time", cumu_value, root.GetAllocator());
1336
0
    rapidjson::Value base_value;
1337
0
    format_str = ToStringFromUnixMillis(_last_base_compaction_failure_millis.load());
1338
0
    base_value.SetString(format_str.c_str(), format_str.length(), root.GetAllocator());
1339
0
    root.AddMember("last base failure time", base_value, root.GetAllocator());
1340
0
    rapidjson::Value full_value;
1341
0
    format_str = ToStringFromUnixMillis(_last_full_compaction_failure_millis.load());
1342
0
    full_value.SetString(format_str.c_str(), format_str.length(), root.GetAllocator());
1343
0
    root.AddMember("last full failure time", full_value, root.GetAllocator());
1344
0
    rapidjson::Value cumu_success_value;
1345
0
    format_str = ToStringFromUnixMillis(_last_cumu_compaction_success_millis.load());
1346
0
    cumu_success_value.SetString(format_str.c_str(), format_str.length(), root.GetAllocator());
1347
0
    root.AddMember("last cumulative success time", cumu_success_value, root.GetAllocator());
1348
0
    rapidjson::Value base_success_value;
1349
0
    format_str = ToStringFromUnixMillis(_last_base_compaction_success_millis.load());
1350
0
    base_success_value.SetString(format_str.c_str(), format_str.length(), root.GetAllocator());
1351
0
    root.AddMember("last base success time", base_success_value, root.GetAllocator());
1352
0
    rapidjson::Value full_success_value;
1353
0
    format_str = ToStringFromUnixMillis(_last_full_compaction_success_millis.load());
1354
0
    full_success_value.SetString(format_str.c_str(), format_str.length(), root.GetAllocator());
1355
0
    root.AddMember("last full success time", full_success_value, root.GetAllocator());
1356
0
    rapidjson::Value cumu_schedule_value;
1357
0
    format_str = ToStringFromUnixMillis(_last_cumu_compaction_schedule_millis.load());
1358
0
    cumu_schedule_value.SetString(format_str.c_str(), format_str.length(), root.GetAllocator());
1359
0
    root.AddMember("last cumulative schedule time", cumu_schedule_value, root.GetAllocator());
1360
0
    rapidjson::Value base_schedule_value;
1361
0
    format_str = ToStringFromUnixMillis(_last_base_compaction_schedule_millis.load());
1362
0
    base_schedule_value.SetString(format_str.c_str(), format_str.length(), root.GetAllocator());
1363
0
    root.AddMember("last base schedule time", base_schedule_value, root.GetAllocator());
1364
0
    rapidjson::Value full_schedule_value;
1365
0
    format_str = ToStringFromUnixMillis(_last_full_compaction_schedule_millis.load());
1366
0
    full_schedule_value.SetString(format_str.c_str(), format_str.length(), root.GetAllocator());
1367
0
    root.AddMember("last full schedule time", full_schedule_value, root.GetAllocator());
1368
0
    rapidjson::Value cumu_compaction_status_value;
1369
0
    cumu_compaction_status_value.SetString(_last_cumu_compaction_status.c_str(),
1370
0
                                           _last_cumu_compaction_status.length(),
1371
0
                                           root.GetAllocator());
1372
0
    root.AddMember("last cumulative status", cumu_compaction_status_value, root.GetAllocator());
1373
0
    rapidjson::Value base_compaction_status_value;
1374
0
    base_compaction_status_value.SetString(_last_base_compaction_status.c_str(),
1375
0
                                           _last_base_compaction_status.length(),
1376
0
                                           root.GetAllocator());
1377
0
    root.AddMember("last base status", base_compaction_status_value, root.GetAllocator());
1378
0
    rapidjson::Value full_compaction_status_value;
1379
0
    full_compaction_status_value.SetString(_last_full_compaction_status.c_str(),
1380
0
                                           _last_full_compaction_status.length(),
1381
0
                                           root.GetAllocator());
1382
0
    root.AddMember("last full status", full_compaction_status_value, root.GetAllocator());
1383
1384
    // last single replica compaction status
1385
    // "single replica compaction status": {
1386
    //     "remote peer": "172.100.1.0:10875",
1387
    //     "last failure status": "",
1388
    //     "last fetched rowset": "[8-10]"
1389
    // }
1390
0
    rapidjson::Document status;
1391
0
    status.SetObject();
1392
0
    TReplicaInfo replica_info;
1393
0
    std::string dummp_token;
1394
0
    if (tablet_meta()->tablet_schema()->enable_single_replica_compaction() &&
  Branch (1394:9): [True: 0, False: 0]
1395
0
        _engine.get_peer_replica_info(tablet_id(), &replica_info, &dummp_token)) {
  Branch (1395:9): [True: 0, False: 0]
1396
        // remote peer
1397
0
        rapidjson::Value peer_addr;
1398
0
        std::string addr = replica_info.host + ":" + std::to_string(replica_info.brpc_port);
1399
0
        peer_addr.SetString(addr.c_str(), addr.length(), status.GetAllocator());
1400
0
        status.AddMember("remote peer", peer_addr, status.GetAllocator());
1401
        // last failure status
1402
0
        rapidjson::Value compaction_status;
1403
0
        compaction_status.SetString(_last_single_compaction_failure_status.c_str(),
1404
0
                                    _last_single_compaction_failure_status.length(),
1405
0
                                    status.GetAllocator());
1406
0
        status.AddMember("last failure status", compaction_status, status.GetAllocator());
1407
        // last fetched rowset
1408
0
        rapidjson::Value version;
1409
0
        std::string fetched_version = _last_fetched_version.to_string();
1410
0
        version.SetString(fetched_version.c_str(), fetched_version.length(), status.GetAllocator());
1411
0
        status.AddMember("last fetched rowset", version, status.GetAllocator());
1412
0
        root.AddMember("single replica compaction status", status, root.GetAllocator());
1413
0
    }
1414
1415
    // print all rowsets' version as an array
1416
0
    rapidjson::Document versions_arr;
1417
0
    rapidjson::Document missing_versions_arr;
1418
0
    versions_arr.SetArray();
1419
0
    missing_versions_arr.SetArray();
1420
0
    int64_t last_version = -1;
1421
0
    for (auto& rowset : rowsets) {
  Branch (1421:23): [True: 0, False: 0]
1422
0
        const Version& ver = rowset->version();
1423
0
        if (ver.first != last_version + 1) {
  Branch (1423:13): [True: 0, False: 0]
1424
0
            rapidjson::Value miss_value;
1425
0
            miss_value.SetString(fmt::format("[{}-{}]", last_version + 1, ver.first - 1).c_str(),
1426
0
                                 missing_versions_arr.GetAllocator());
1427
0
            missing_versions_arr.PushBack(miss_value, missing_versions_arr.GetAllocator());
1428
0
        }
1429
0
        rapidjson::Value value;
1430
0
        std::string version_str = rowset->get_rowset_info_str();
1431
0
        value.SetString(version_str.c_str(), version_str.length(), versions_arr.GetAllocator());
1432
0
        versions_arr.PushBack(value, versions_arr.GetAllocator());
1433
0
        last_version = ver.second;
1434
0
    }
1435
0
    root.AddMember("rowsets", versions_arr, root.GetAllocator());
1436
0
    root.AddMember("missing_rowsets", missing_versions_arr, root.GetAllocator());
1437
1438
    // print all stale rowsets' version as an array
1439
0
    rapidjson::Document stale_versions_arr;
1440
0
    stale_versions_arr.SetArray();
1441
0
    for (auto& rowset : stale_rowsets) {
  Branch (1441:23): [True: 0, False: 0]
1442
0
        rapidjson::Value value;
1443
0
        std::string version_str = rowset->get_rowset_info_str();
1444
0
        value.SetString(version_str.c_str(), version_str.length(),
1445
0
                        stale_versions_arr.GetAllocator());
1446
0
        stale_versions_arr.PushBack(value, stale_versions_arr.GetAllocator());
1447
0
    }
1448
0
    root.AddMember("stale_rowsets", stale_versions_arr, root.GetAllocator());
1449
1450
    // add stale version rowsets
1451
0
    root.AddMember("stale version path", path_arr, root.GetAllocator());
1452
1453
    // to json string
1454
0
    rapidjson::StringBuffer strbuf;
1455
0
    rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(strbuf);
1456
0
    root.Accept(writer);
1457
0
    *json_result = std::string(strbuf.GetString());
1458
0
}
1459
1460
1
bool Tablet::do_tablet_meta_checkpoint() {
1461
1
    std::lock_guard<std::shared_mutex> store_lock(_meta_store_lock);
1462
1
    if (_newly_created_rowset_num == 0) {
  Branch (1462:9): [True: 0, False: 1]
1463
0
        return false;
1464
0
    }
1465
1
    if (UnixMillis() - _last_checkpoint_time <
  Branch (1465:9): [True: 0, False: 1]
1466
1
                config::tablet_meta_checkpoint_min_interval_secs * 1000 &&
1467
1
        _newly_created_rowset_num < config::tablet_meta_checkpoint_min_new_rowsets_num) {
  Branch (1467:9): [True: 0, False: 0]
1468
0
        return false;
1469
0
    }
1470
    // hold read-lock other than write-lock, because it will not modify meta structure
1471
1
    std::shared_lock rdlock(_meta_lock);
1472
1
    if (tablet_state() != TABLET_RUNNING) {
  Branch (1472:9): [True: 1, False: 0]
1473
1
        LOG(INFO) << "tablet is under state=" << tablet_state()
1474
1
                  << ", not running, skip do checkpoint"
1475
1
                  << ", tablet=" << tablet_id();
1476
1
        return false;
1477
1
    }
1478
0
    VLOG_NOTICE << "start to do tablet meta checkpoint, tablet=" << tablet_id();
Line
Count
Source
42
0
#define VLOG_NOTICE VLOG(3)
1479
0
    save_meta();
1480
    // if save meta successfully, then should remove the rowset meta existing in tablet
1481
    // meta from rowset meta store
1482
0
    for (auto& rs_meta : _tablet_meta->all_rs_metas()) {
  Branch (1482:24): [True: 0, False: 0]
1483
        // If we delete it from rowset manager's meta explicitly in previous checkpoint, just skip.
1484
0
        if (rs_meta->is_remove_from_rowset_meta()) {
  Branch (1484:13): [True: 0, False: 0]
1485
0
            continue;
1486
0
        }
1487
0
        if (RowsetMetaManager::check_rowset_meta(_data_dir->get_meta(), tablet_uid(),
  Branch (1487:13): [True: 0, False: 0]
1488
0
                                                 rs_meta->rowset_id())) {
1489
0
            RETURN_FALSE_IF_ERROR(RowsetMetaManager::remove(_data_dir->get_meta(), tablet_uid(),
Line
Count
Source
677
0
    do {                              \
678
0
        Status status = (stmt);       \
679
0
        if (UNLIKELY(!status.ok())) { \
Line
Count
Source
36
0
#define UNLIKELY(expr) __builtin_expect(!!(expr), 0)
  Branch (36:24): [True: 0, False: 0]
680
0
            return false;             \
681
0
        }                             \
682
0
    } while (false)
  Branch (682:14): [Folded - Ignored]
1490
0
                                                            rs_meta->rowset_id()));
1491
0
            VLOG_NOTICE << "remove rowset id from meta store because it is already persistent with "
Line
Count
Source
42
0
#define VLOG_NOTICE VLOG(3)
1492
0
                        << "tablet meta, rowset_id=" << rs_meta->rowset_id();
1493
0
        }
1494
0
        rs_meta->set_remove_from_rowset_meta();
1495
0
    }
1496
1497
    // check _stale_rs_version_map to remove meta from rowset meta store
1498
0
    for (auto& rs_meta : _tablet_meta->all_stale_rs_metas()) {
  Branch (1498:24): [True: 0, False: 0]
1499
        // If we delete it from rowset manager's meta explicitly in previous checkpoint, just skip.
1500
0
        if (rs_meta->is_remove_from_rowset_meta()) {
  Branch (1500:13): [True: 0, False: 0]
1501
0
            continue;
1502
0
        }
1503
0
        if (RowsetMetaManager::check_rowset_meta(_data_dir->get_meta(), tablet_uid(),
  Branch (1503:13): [True: 0, False: 0]
1504
0
                                                 rs_meta->rowset_id())) {
1505
0
            RETURN_FALSE_IF_ERROR(RowsetMetaManager::remove(_data_dir->get_meta(), tablet_uid(),
Line
Count
Source
677
0
    do {                              \
678
0
        Status status = (stmt);       \
679
0
        if (UNLIKELY(!status.ok())) { \
Line
Count
Source
36
0
#define UNLIKELY(expr) __builtin_expect(!!(expr), 0)
  Branch (36:24): [True: 0, False: 0]
680
0
            return false;             \
681
0
        }                             \
682
0
    } while (false)
  Branch (682:14): [Folded - Ignored]
1506
0
                                                            rs_meta->rowset_id()));
1507
0
            VLOG_NOTICE << "remove rowset id from meta store because it is already persistent with "
Line
Count
Source
42
0
#define VLOG_NOTICE VLOG(3)
1508
0
                        << "tablet meta, rowset_id=" << rs_meta->rowset_id();
1509
0
        }
1510
0
        rs_meta->set_remove_from_rowset_meta();
1511
0
    }
1512
1513
0
    if (keys_type() == UNIQUE_KEYS && enable_unique_key_merge_on_write()) {
  Branch (1513:9): [True: 0, False: 0]
  Branch (1513:39): [True: 0, False: 0]
1514
0
        RETURN_FALSE_IF_ERROR(TabletMetaManager::remove_old_version_delete_bitmap(
Line
Count
Source
677
0
    do {                              \
678
0
        Status status = (stmt);       \
679
0
        if (UNLIKELY(!status.ok())) { \
Line
Count
Source
36
0
#define UNLIKELY(expr) __builtin_expect(!!(expr), 0)
  Branch (36:24): [True: 0, False: 0]
680
0
            return false;             \
681
0
        }                             \
682
0
    } while (false)
  Branch (682:14): [Folded - Ignored]
1515
0
                _data_dir, tablet_id(), max_version_unlocked()));
1516
0
    }
1517
1518
0
    _newly_created_rowset_num = 0;
1519
0
    _last_checkpoint_time = UnixMillis();
1520
0
    return true;
1521
0
}
1522
1523
0
bool Tablet::rowset_meta_is_useful(RowsetMetaSharedPtr rowset_meta) {
1524
0
    std::shared_lock rdlock(_meta_lock);
1525
0
    bool find_version = false;
1526
0
    for (auto& version_rowset : _rs_version_map) {
  Branch (1526:31): [True: 0, False: 0]
1527
0
        if (version_rowset.second->rowset_id() == rowset_meta->rowset_id()) {
  Branch (1527:13): [True: 0, False: 0]
1528
0
            return true;
1529
0
        }
1530
0
        if (version_rowset.second->contains_version(rowset_meta->version())) {
  Branch (1530:13): [True: 0, False: 0]
1531
0
            find_version = true;
1532
0
        }
1533
0
    }
1534
0
    for (auto& stale_version_rowset : _stale_rs_version_map) {
  Branch (1534:37): [True: 0, False: 0]
1535
0
        if (stale_version_rowset.second->rowset_id() == rowset_meta->rowset_id()) {
  Branch (1535:13): [True: 0, False: 0]
1536
0
            return true;
1537
0
        }
1538
0
        if (stale_version_rowset.second->contains_version(rowset_meta->version())) {
  Branch (1538:13): [True: 0, False: 0]
1539
0
            find_version = true;
1540
0
        }
1541
0
    }
1542
0
    return !find_version;
1543
0
}
1544
1545
10.9k
bool Tablet::_contains_rowset(const RowsetId rowset_id) {
1546
356k
    for (auto& version_rowset : _rs_version_map) {
  Branch (1546:31): [True: 356k, False: 10.9k]
1547
356k
        if (version_rowset.second->rowset_id() == rowset_id) {
  Branch (1547:13): [True: 0, False: 356k]
1548
0
            return true;
1549
0
        }
1550
356k
    }
1551
10.9k
    for (auto& stale_version_rowset : _stale_rs_version_map) {
  Branch (1551:37): [True: 0, False: 10.9k]
1552
0
        if (stale_version_rowset.second->rowset_id() == rowset_id) {
  Branch (1552:13): [True: 0, False: 0]
1553
0
            return true;
1554
0
        }
1555
0
    }
1556
10.9k
    return false;
1557
10.9k
}
1558
1559
// need check if consecutive version missing in full report
1560
// alter tablet will ignore this check
1561
void Tablet::build_tablet_report_info(TTabletInfo* tablet_info,
1562
                                      bool enable_consecutive_missing_check,
1563
0
                                      bool enable_path_check) {
1564
0
    std::shared_lock rdlock(_meta_lock);
1565
0
    tablet_info->__set_tablet_id(_tablet_meta->tablet_id());
1566
0
    tablet_info->__set_schema_hash(_tablet_meta->schema_hash());
1567
0
    tablet_info->__set_row_count(_tablet_meta->num_rows());
1568
0
    tablet_info->__set_data_size(_tablet_meta->tablet_local_size());
1569
1570
    // Here we need to report to FE if there are any missing versions of tablet.
1571
    // We start from the initial version and traverse backwards until we meet a discontinuous version.
1572
0
    Version cversion;
1573
0
    Version max_version;
1574
0
    bool has_version_cross;
1575
0
    _max_continuous_version_from_beginning_unlocked(&cversion, &max_version, &has_version_cross);
1576
    // cause publish version task runs concurrently, version may be flying
1577
    // so we add a consecutive miss check to solve this problem:
1578
    // if publish version 5 arrives but version 4 flying, we may judge replica miss version
1579
    // and set version miss in tablet_info, which makes fe treat this replica as unhealth
1580
    // and lead to other problems
1581
0
    if (enable_consecutive_missing_check) {
  Branch (1581:9): [True: 0, False: 0]
1582
0
        if (cversion.second < max_version.second) {
  Branch (1582:13): [True: 0, False: 0]
1583
0
            if (_last_missed_version == cversion.second + 1) {
  Branch (1583:17): [True: 0, False: 0]
1584
0
                if (MonotonicSeconds() - _last_missed_time_s >= 60) {
  Branch (1584:21): [True: 0, False: 0]
1585
                    // version missed for over 60 seconds
1586
0
                    tablet_info->__set_version_miss(true);
1587
0
                    _last_missed_version = -1;
1588
0
                    _last_missed_time_s = 0;
1589
0
                }
1590
0
            } else {
1591
0
                _last_missed_version = cversion.second + 1;
1592
0
                _last_missed_time_s = MonotonicSeconds();
1593
0
            }
1594
0
        }
1595
0
    } else {
1596
0
        tablet_info->__set_version_miss(cversion.second < max_version.second);
1597
0
    }
1598
1599
0
    DBUG_EXECUTE_IF("Tablet.build_tablet_report_info.version_miss", {
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]
  Branch (41:15): [True: 0, False: 0]
42
0
        }                                                                     \
43
0
    }
1600
0
        auto tablet_id = dp->param<int64>("tablet_id", -1);
1601
0
        if (tablet_id != -1 && tablet_id == _tablet_meta->tablet_id()) {
1602
0
            auto miss = dp->param<bool>("version_miss", true);
1603
0
            tablet_info->__set_version_miss(miss);
1604
0
        }
1605
0
    });
1606
1607
    // find rowset with max version
1608
0
    auto iter = _rs_version_map.find(max_version);
1609
0
    if (iter == _rs_version_map.end()) {
  Branch (1609:9): [True: 0, False: 0]
1610
        // If the tablet is in running state, it must not be doing schema-change. so if we can not
1611
        // access its rowsets, it means that the tablet is bad and needs to be reported to the FE
1612
        // for subsequent repairs (through the cloning task)
1613
0
        if (tablet_state() == TABLET_RUNNING) {
  Branch (1613:13): [True: 0, False: 0]
1614
0
            tablet_info->__set_used(false);
1615
0
        }
1616
        // For other states, FE knows that the tablet is in a certain change process, so here
1617
        // still sets the state to normal when reporting. Note that every task has an timeout,
1618
        // so if the task corresponding to this change hangs, when the task timeout, FE will know
1619
        // and perform state modification operations.
1620
0
    }
1621
1622
0
    if (tablet_state() == TABLET_RUNNING) {
  Branch (1622:9): [True: 0, False: 0]
1623
0
        if (has_version_cross || is_io_error_too_times() || !data_dir()->is_used()) {
  Branch (1623:13): [True: 0, False: 0]
  Branch (1623:34): [True: 0, False: 0]
  Branch (1623:61): [True: 0, False: 0]
1624
0
            LOG(INFO) << "report " << tablet_id() << " as bad, version_cross=" << has_version_cross
1625
0
                      << ", ioe times=" << get_io_error_times() << ", data_dir used "
1626
0
                      << data_dir()->is_used();
1627
0
            tablet_info->__set_used(false);
1628
0
        }
1629
1630
0
        if (enable_path_check) {
  Branch (1630:13): [True: 0, False: 0]
1631
0
            if (!_is_tablet_path_exists.exchange(true, std::memory_order_relaxed)) {
  Branch (1631:17): [True: 0, False: 0]
1632
0
                LOG(INFO) << "report " << tablet_id() << " as bad, tablet directory not found";
1633
0
                tablet_info->__set_used(false);
1634
0
            }
1635
0
        }
1636
0
    }
1637
1638
    // There are two cases when tablet state is TABLET_NOTREADY
1639
    // case 1: tablet is doing schema change. Fe knows it's state, doing nothing.
1640
    // case 2: tablet has finished schema change, but failed. Fe will perform recovery.
1641
0
    if (tablet_state() == TABLET_NOTREADY && is_alter_failed()) {
  Branch (1641:9): [True: 0, False: 0]
  Branch (1641:46): [True: 0, False: 0]
1642
0
        tablet_info->__set_used(false);
1643
0
    }
1644
1645
0
    if (tablet_state() == TABLET_SHUTDOWN) {
  Branch (1645:9): [True: 0, False: 0]
1646
0
        tablet_info->__set_used(false);
1647
0
    }
1648
1649
0
    DBUG_EXECUTE_IF("Tablet.build_tablet_report_info.used", {
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]
  Branch (41:15): [True: 0, False: 0]
42
0
        }                                                                     \
43
0
    }
1650
0
        auto tablet_id = dp->param<int64>("tablet_id", -1);
1651
0
        if (tablet_id != -1 && tablet_id == _tablet_meta->tablet_id()) {
1652
0
            auto used = dp->param<bool>("used", true);
1653
0
            LOG_WARNING("Tablet.build_tablet_report_info.used")
1654
0
                    .tag("tablet id", tablet_id)
1655
0
                    .tag("used", used);
1656
0
            tablet_info->__set_used(used);
1657
0
        } else {
1658
0
            LOG_WARNING("Tablet.build_tablet_report_info.used").tag("tablet id", tablet_id);
1659
0
        }
1660
0
    });
1661
1662
0
    int64_t total_version_count = _tablet_meta->version_count();
1663
1664
    // For compatibility.
1665
    // For old fe, it wouldn't send visible version request to be, then be's visible version is always 0.
1666
    // Let visible_version_count set to total_version_count in be's report.
1667
0
    int64_t visible_version_count = total_version_count;
1668
0
    if (auto [visible_version, _] = get_visible_version_and_time(); visible_version > 0) {
  Branch (1668:69): [True: 0, False: 0]
1669
0
        visible_version_count = _tablet_meta->version_count_cross_with_range({0, visible_version});
1670
0
    }
1671
    // the report version is the largest continuous version, same logic as in FE side
1672
0
    tablet_info->__set_version(cversion.second);
1673
    // Useless but it is a required filed in TTabletInfo
1674
0
    tablet_info->__set_version_hash(0);
1675
0
    tablet_info->__set_partition_id(_tablet_meta->partition_id());
1676
0
    tablet_info->__set_storage_medium(_data_dir->storage_medium());
1677
0
    tablet_info->__set_total_version_count(total_version_count);
1678
0
    tablet_info->__set_visible_version_count(visible_version_count);
1679
0
    tablet_info->__set_path_hash(_data_dir->path_hash());
1680
0
    tablet_info->__set_is_in_memory(_tablet_meta->tablet_schema()->is_in_memory());
1681
0
    tablet_info->__set_replica_id(replica_id());
1682
0
    tablet_info->__set_remote_data_size(_tablet_meta->tablet_remote_size());
1683
0
    if (_tablet_meta->cooldown_meta_id().initialized()) { // has cooldowned data
  Branch (1683:9): [True: 0, False: 0]
1684
0
        tablet_info->__set_cooldown_term(_cooldown_conf.term);
1685
0
        tablet_info->__set_cooldown_meta_id(_tablet_meta->cooldown_meta_id().to_thrift());
1686
0
    }
1687
0
    if (tablet_state() == TABLET_RUNNING && _tablet_meta->storage_policy_id() > 0) {
  Branch (1687:9): [True: 0, False: 0]
  Branch (1687:45): [True: 0, False: 0]
1688
        // tablet may not have cooldowned data, but the storage policy is set
1689
0
        tablet_info->__set_cooldown_term(_cooldown_conf.term);
1690
0
    }
1691
0
    tablet_info->__set_local_index_size(_tablet_meta->tablet_local_index_size());
1692
0
    tablet_info->__set_local_segment_size(_tablet_meta->tablet_local_segment_size());
1693
0
    tablet_info->__set_remote_index_size(_tablet_meta->tablet_remote_index_size());
1694
0
    tablet_info->__set_remote_segment_size(_tablet_meta->tablet_remote_segment_size());
1695
0
}
1696
1697
2
void Tablet::report_error(const Status& st) {
1698
2
    if (st.is<ErrorCode::IO_ERROR>()) {
  Branch (1698:9): [True: 0, False: 2]
1699
0
        ++_io_error_times;
1700
2
    } else if (st.is<ErrorCode::CORRUPTION>()) {
  Branch (1700:16): [True: 1, False: 1]
1701
1
        _io_error_times = config::max_tablet_io_errors + 1;
1702
1
    } else if (st.is<ErrorCode::NOT_FOUND>()) {
  Branch (1702:16): [True: 0, False: 1]
1703
0
        check_tablet_path_exists();
1704
0
        if (!_is_tablet_path_exists.load(std::memory_order_relaxed)) {
  Branch (1704:13): [True: 0, False: 0]
1705
0
            _io_error_times = config::max_tablet_io_errors + 1;
1706
0
        }
1707
0
    }
1708
2
}
1709
1710
Status Tablet::prepare_compaction_and_calculate_permits(
1711
        CompactionType compaction_type, const TabletSharedPtr& tablet,
1712
21
        std::shared_ptr<CompactionMixin>& compaction, int64_t& permits) {
1713
21
    if (compaction_type == CompactionType::CUMULATIVE_COMPACTION) {
  Branch (1713:9): [True: 21, False: 0]
1714
21
        MonotonicStopWatch watch;
1715
21
        watch.start();
1716
1717
21
        compaction = std::make_shared<CumulativeCompaction>(tablet->_engine, tablet);
1718
21
        DorisMetrics::instance()->cumulative_compaction_request_total->increment(1);
1719
21
        Status res = compaction->prepare_compact();
1720
21
        if (!config::disable_compaction_trace_log &&
  Branch (1720:13): [True: 0, False: 21]
1721
21
            watch.elapsed_time() / 1e9 > config::cumulative_compaction_trace_threshold) {
  Branch (1721:13): [True: 0, False: 0]
1722
0
            std::stringstream ss;
1723
0
            compaction->runtime_profile()->pretty_print(&ss);
1724
0
            LOG(WARNING) << "prepare cumulative compaction cost " << watch.elapsed_time() / 1e9
1725
0
                         << std::endl
1726
0
                         << ss.str();
1727
0
        }
1728
1729
21
        if (!res.ok()) {
  Branch (1729:13): [True: 0, False: 21]
1730
0
            permits = 0;
1731
            // if we meet a delete version, should increase the cumulative point to let base compaction handle the delete version.
1732
            // no need to wait 5s.
1733
0
            if (!res.is<ErrorCode::CUMULATIVE_MEET_DELETE_VERSION>() ||
  Branch (1733:17): [True: 0, False: 0]
1734
0
                config::enable_sleep_between_delete_cumu_compaction) {
  Branch (1734:17): [True: 0, False: 0]
1735
0
                tablet->set_last_cumu_compaction_failure_time(UnixMillis());
1736
0
            }
1737
0
            if (!res.is<CUMULATIVE_NO_SUITABLE_VERSION>() &&
  Branch (1737:17): [True: 0, False: 0]
1738
0
                !res.is<ErrorCode::CUMULATIVE_MEET_DELETE_VERSION>()) {
  Branch (1738:17): [True: 0, False: 0]
1739
0
                DorisMetrics::instance()->cumulative_compaction_request_failed->increment(1);
1740
0
                return Status::InternalError("prepare cumulative compaction with err: {}",
1741
0
                                             res.to_string());
1742
0
            }
1743
            // return OK if OLAP_ERR_CUMULATIVE_NO_SUITABLE_VERSION, so that we don't need to
1744
            // print too much useless logs.
1745
            // And because we set permits to 0, so even if we return OK here, nothing will be done.
1746
0
            return Status::OK();
1747
0
        }
1748
21
    } else if (compaction_type == CompactionType::BASE_COMPACTION) {
  Branch (1748:16): [True: 0, False: 0]
1749
0
        MonotonicStopWatch watch;
1750
0
        watch.start();
1751
1752
0
        compaction = std::make_shared<BaseCompaction>(tablet->_engine, tablet);
1753
0
        DorisMetrics::instance()->base_compaction_request_total->increment(1);
1754
0
        Status res = compaction->prepare_compact();
1755
0
        if (!config::disable_compaction_trace_log &&
  Branch (1755:13): [True: 0, False: 0]
1756
0
            watch.elapsed_time() / 1e9 > config::base_compaction_trace_threshold) {
  Branch (1756:13): [True: 0, False: 0]
1757
0
            std::stringstream ss;
1758
0
            compaction->runtime_profile()->pretty_print(&ss);
1759
0
            LOG(WARNING) << "prepare base compaction cost " << watch.elapsed_time() / 1e9
1760
0
                         << std::endl
1761
0
                         << ss.str();
1762
0
        }
1763
1764
0
        tablet->set_last_base_compaction_status(res.to_string());
1765
0
        if (!res.ok()) {
  Branch (1765:13): [True: 0, False: 0]
1766
0
            tablet->set_last_base_compaction_failure_time(UnixMillis());
1767
0
            permits = 0;
1768
0
            if (!res.is<BE_NO_SUITABLE_VERSION>()) {
  Branch (1768:17): [True: 0, False: 0]
1769
0
                DorisMetrics::instance()->base_compaction_request_failed->increment(1);
1770
0
                return Status::InternalError("prepare base compaction with err: {}",
1771
0
                                             res.to_string());
1772
0
            }
1773
            // return OK if OLAP_ERR_BE_NO_SUITABLE_VERSION, so that we don't need to
1774
            // print too much useless logs.
1775
            // And because we set permits to 0, so even if we return OK here, nothing will be done.
1776
0
            return Status::OK();
1777
0
        }
1778
0
    } else {
1779
0
        DCHECK_EQ(compaction_type, CompactionType::FULL_COMPACTION);
1780
1781
0
        compaction = std::make_shared<FullCompaction>(tablet->_engine, tablet);
1782
0
        Status res = compaction->prepare_compact();
1783
0
        if (!res.ok()) {
  Branch (1783:13): [True: 0, False: 0]
1784
0
            tablet->set_last_full_compaction_failure_time(UnixMillis());
1785
0
            permits = 0;
1786
0
            if (!res.is<FULL_NO_SUITABLE_VERSION>()) {
  Branch (1786:17): [True: 0, False: 0]
1787
0
                return Status::InternalError("prepare full compaction with err: {}",
1788
0
                                             res.to_string());
1789
0
            }
1790
            // return OK if OLAP_ERR_BE_NO_SUITABLE_VERSION, so that we don't need to
1791
            // print too much useless logs.
1792
            // And because we set permits to 0, so even if we return OK here, nothing will be done.
1793
0
            return Status::OK();
1794
0
        }
1795
0
    }
1796
1797
    // Time series policy does not rely on permits, it uses goal size to control memory
1798
21
    if (tablet->tablet_meta()->compaction_policy() == CUMULATIVE_TIME_SERIES_POLICY) {
  Branch (1798:9): [True: 0, False: 21]
1799
        // permits = 0 means that prepare_compaction failed
1800
0
        permits = 1;
1801
21
    } else {
1802
21
        permits = compaction->get_compaction_permits();
1803
21
    }
1804
21
    return Status::OK();
1805
21
}
1806
1807
0
void Tablet::execute_single_replica_compaction(SingleReplicaCompaction& compaction) {
1808
0
    Status res = compaction.execute_compact();
1809
0
    if (!res.ok()) {
  Branch (1809:9): [True: 0, False: 0]
1810
0
        set_last_failure_time(this, compaction, UnixMillis());
1811
0
        set_last_single_compaction_failure_status(res.to_string());
1812
0
        if (res.is<CANCELLED>()) {
  Branch (1812:13): [True: 0, False: 0]
1813
0
            DorisMetrics::instance()->single_compaction_request_cancelled->increment(1);
1814
            // "CANCELLED" indicates that the peer has not performed compaction,
1815
            // wait for the peer to perform compaction
1816
0
            set_skip_compaction(true, compaction.real_compact_type(), UnixSeconds());
1817
0
            VLOG_CRITICAL << "Cannel fetching from the remote peer. res=" << res
Line
Count
Source
43
0
#define VLOG_CRITICAL VLOG(1)
1818
0
                          << ", tablet=" << tablet_id();
1819
0
        } else {
1820
0
            DorisMetrics::instance()->single_compaction_request_failed->increment(1);
1821
0
            LOG(WARNING) << "failed to do single replica compaction. res=" << res
1822
0
                         << ", tablet=" << tablet_id();
1823
0
        }
1824
0
        return;
1825
0
    }
1826
0
    set_last_failure_time(this, compaction, 0);
1827
0
}
1828
1829
327
bool Tablet::should_fetch_from_peer() {
1830
327
    return tablet_meta()->tablet_schema()->enable_single_replica_compaction() &&
  Branch (1830:12): [True: 7, False: 320]
1831
327
           _engine.should_fetch_from_peer(tablet_id());
  Branch (1831:12): [True: 6, False: 1]
1832
327
}
1833
1834
3
std::vector<Version> Tablet::get_all_local_versions() {
1835
3
    std::vector<Version> local_versions;
1836
3
    {
1837
3
        std::shared_lock rlock(_meta_lock);
1838
63
        for (const auto& [version, rs] : _rs_version_map) {
  Branch (1838:40): [True: 63, False: 3]
1839
63
            if (rs->is_local()) {
  Branch (1839:17): [True: 53, False: 10]
1840
53
                local_versions.emplace_back(version);
1841
53
            }
1842
63
        }
1843
3
    }
1844
3
    std::sort(local_versions.begin(), local_versions.end(),
1845
318
              [](const Version& left, const Version& right) { return left.first < right.first; });
1846
3
    return local_versions;
1847
3
}
1848
1849
1
void Tablet::execute_compaction(CompactionMixin& compaction) {
1850
1
    signal::tablet_id = tablet_id();
1851
1852
1
    MonotonicStopWatch watch;
1853
1
    watch.start();
1854
1855
1
    Status res = [&]() { RETURN_IF_CATCH_EXCEPTION({ return compaction.execute_compact(); }); }();
Line
Count
Source
80
1
    do {                                                                                         \
81
1
        try {                                                                                    \
82
1
            doris::enable_thread_catch_bad_alloc++;                                              \
83
1
            Defer defer {[&]() { doris::enable_thread_catch_bad_alloc--; }};                     \
84
1
            { stmt; }                                                                            \
85
0
        } catch (const doris::Exception& e) {                                                    \
86
0
            if (e.code() == doris::ErrorCode::MEM_ALLOC_FAILED) {                                \
  Branch (86:17): [True: 0, False: 0]
87
0
                return Status::MemoryLimitExceeded(fmt::format(                                  \
88
0
                        "PreCatch error code:{}, {}, __FILE__:{}, __LINE__:{}, __FUNCTION__:{}", \
89
0
                        e.code(), e.to_string(), __FILE__, __LINE__, __PRETTY_FUNCTION__));      \
90
0
            }                                                                                    \
91
0
            return Status::Error<false>(e.code(), e.to_string());                                \
92
0
        }                                                                                        \
93
1
    } while (0)
  Branch (93:14): [Folded - Ignored]
1856
1
    if (!res.ok()) [[unlikely]] {
  Branch (1856:9): [True: 0, False: 1]
1857
0
        set_last_failure_time(this, compaction, UnixMillis());
1858
0
        LOG(WARNING) << "failed to do " << compaction.compaction_name()
1859
0
                     << ", tablet=" << tablet_id() << " : " << res;
1860
1
    } else {
1861
1
        set_last_failure_time(this, compaction, 0);
1862
1
    }
1863
1864
1
    if (!config::disable_compaction_trace_log) {
  Branch (1864:9): [True: 0, False: 1]
1865
0
        auto need_trace = [&compaction, &watch] {
1866
0
            return compaction.compaction_type() == ReaderType::READER_CUMULATIVE_COMPACTION
  Branch (1866:20): [True: 0, False: 0]
1867
0
                           ? watch.elapsed_time() / 1e9 >
1868
0
                                     config::cumulative_compaction_trace_threshold
1869
0
                   : compaction.compaction_type() == ReaderType::READER_BASE_COMPACTION
  Branch (1869:22): [True: 0, False: 0]
1870
0
                           ? watch.elapsed_time() / 1e9 > config::base_compaction_trace_threshold
1871
0
                           : false;
1872
0
        };
1873
0
        if (need_trace()) {
  Branch (1873:13): [True: 0, False: 0]
1874
0
            std::stringstream ss;
1875
0
            compaction.runtime_profile()->pretty_print(&ss);
1876
0
            LOG(WARNING) << "execute " << compaction.compaction_name() << " cost "
1877
0
                         << watch.elapsed_time() / 1e9 << std::endl
1878
0
                         << ss.str();
1879
0
        }
1880
0
    }
1881
1
}
1882
1883
300
Status Tablet::create_initial_rowset(const int64_t req_version) {
1884
300
    if (req_version < 1) {
  Branch (1884:9): [True: 0, False: 300]
1885
0
        return Status::Error<CE_CMD_PARAMS_ERROR>(
1886
0
                "init version of tablet should at least 1. req.ver={}", req_version);
1887
0
    }
1888
300
    Version version(0, req_version);
1889
300
    RowsetSharedPtr new_rowset;
1890
    // there is no data in init rowset, so overlapping info is unknown.
1891
300
    RowsetWriterContext context;
1892
300
    context.version = version;
1893
300
    context.rowset_state = VISIBLE;
1894
300
    context.segments_overlap = OVERLAP_UNKNOWN;
1895
300
    context.tablet_schema = tablet_schema();
1896
300
    context.newest_write_timestamp = UnixSeconds();
1897
300
    auto rs_writer = DORIS_TRY(create_rowset_writer(context, false));
Line
Count
Source
716
300
    ({                                           \
717
300
        auto&& res = (stmt);                     \
718
300
        using T = std::decay_t<decltype(res)>;   \
719
300
        if (!res.has_value()) [[unlikely]] {     \
  Branch (719:13): [True: 0, False: 300]
720
0
            return std::forward<T>(res).error(); \
721
0
        }                                        \
722
300
        std::forward<T>(res).value();            \
723
300
    });
1898
300
    RETURN_IF_ERROR(rs_writer->flush());
Line
Count
Source
637
300
    do {                                \
638
300
        Status _status_ = (stmt);       \
639
300
        if (UNLIKELY(!_status_.ok())) { \
Line
Count
Source
36
300
#define UNLIKELY(expr) __builtin_expect(!!(expr), 0)
  Branch (36:24): [True: 0, False: 300]
640
0
            return _status_;            \
641
0
        }                               \
642
300
    } while (false)
  Branch (642:14): [Folded - Ignored]
1899
300
    RETURN_IF_ERROR(rs_writer->build(new_rowset));
Line
Count
Source
637
300
    do {                                \
638
300
        Status _status_ = (stmt);       \
639
300
        if (UNLIKELY(!_status_.ok())) { \
Line
Count
Source
36
300
#define UNLIKELY(expr) __builtin_expect(!!(expr), 0)
  Branch (36:24): [True: 0, False: 300]
640
0
            return _status_;            \
641
0
        }                               \
642
300
    } while (false)
  Branch (642:14): [Folded - Ignored]
1900
300
    RETURN_IF_ERROR(add_rowset(std::move(new_rowset)));
Line
Count
Source
637
300
    do {                                \
638
300
        Status _status_ = (stmt);       \
639
300
        if (UNLIKELY(!_status_.ok())) { \
Line
Count
Source
36
300
#define UNLIKELY(expr) __builtin_expect(!!(expr), 0)
  Branch (36:24): [True: 0, False: 300]
640
0
            return _status_;            \
641
0
        }                               \
642
300
    } while (false)
  Branch (642:14): [Folded - Ignored]
1901
300
    set_cumulative_layer_point(req_version + 1);
1902
300
    return Status::OK();
1903
300
}
1904
1905
Result<std::unique_ptr<RowsetWriter>> Tablet::create_rowset_writer(RowsetWriterContext& context,
1906
388
                                                                   bool vertical) {
1907
388
    context.rowset_id = _engine.next_rowset_id();
1908
388
    _init_context_common_fields(context);
1909
388
    return RowsetFactory::create_rowset_writer(_engine, context, vertical);
1910
388
}
1911
1912
// create a rowset writer with rowset_id and seg_id
1913
// after writer, merge this transient rowset with original rowset
1914
Result<std::unique_ptr<RowsetWriter>> Tablet::create_transient_rowset_writer(
1915
        const Rowset& rowset, std::shared_ptr<PartialUpdateInfo> partial_update_info,
1916
0
        int64_t txn_expiration) {
1917
0
    RowsetWriterContext context;
1918
0
    context.rowset_state = PREPARED;
1919
0
    context.segments_overlap = OVERLAPPING;
1920
0
    context.tablet_schema = std::make_shared<TabletSchema>();
1921
    // During a partial update, the extracted columns of a variant should not be included in the tablet schema.
1922
    // This is because the partial update for a variant needs to ignore the extracted columns.
1923
    // Otherwise, the schema types in different rowsets might be inconsistent. When performing a partial update,
1924
    // the complete variant is constructed by reading all the sub-columns of the variant.
1925
0
    context.tablet_schema = rowset.tablet_schema()->copy_without_variant_extracted_columns();
1926
0
    context.newest_write_timestamp = UnixSeconds();
1927
0
    context.tablet_id = table_id();
1928
0
    context.enable_segcompaction = false;
1929
    // ATTN: context.tablet is a shared_ptr, can't simply set it's value to `this`. We should
1930
    // get the shared_ptr from tablet_manager.
1931
0
    auto tablet = _engine.tablet_manager()->get_tablet(tablet_id());
1932
0
    if (!tablet) {
  Branch (1932:9): [True: 0, False: 0]
1933
0
        LOG(WARNING) << "cant find tablet by tablet_id=" << tablet_id();
1934
0
        return ResultError(Status::NotFound("cant find tablet by tablet_id={}", tablet_id()));
1935
0
    }
1936
0
    context.tablet = tablet;
1937
0
    context.write_type = DataWriteType::TYPE_DIRECT;
1938
0
    context.partial_update_info = std::move(partial_update_info);
1939
0
    context.is_transient_rowset_writer = true;
1940
0
    return create_transient_rowset_writer(context, rowset.rowset_id())
1941
0
            .transform([&](auto&& writer) {
1942
0
                writer->set_segment_start_id(rowset.num_segments());
1943
0
                return writer;
1944
0
            });
1945
0
}
1946
1947
Result<std::unique_ptr<RowsetWriter>> Tablet::create_transient_rowset_writer(
1948
0
        RowsetWriterContext& context, const RowsetId& rowset_id) {
1949
0
    context.rowset_id = rowset_id;
1950
0
    _init_context_common_fields(context);
1951
0
    return RowsetFactory::create_rowset_writer(_engine, context, false);
1952
0
}
1953
1954
388
void Tablet::_init_context_common_fields(RowsetWriterContext& context) {
1955
388
    context.tablet_uid = tablet_uid();
1956
388
    context.tablet_id = tablet_id();
1957
388
    context.partition_id = partition_id();
1958
388
    context.tablet_schema_hash = schema_hash();
1959
388
    context.rowset_type = tablet_meta()->preferred_rowset_type();
1960
    // Alpha Rowset will be removed in the future, so that if the tablet's default rowset type is
1961
    // alpha rowset, then set the newly created rowset to storage engine's default rowset.
1962
388
    if (context.rowset_type == ALPHA_ROWSET) {
  Branch (1962:9): [True: 0, False: 388]
1963
0
        context.rowset_type = _engine.default_rowset_type();
1964
0
    }
1965
1966
388
    if (context.is_local_rowset()) {
  Branch (1966:9): [True: 388, False: 0]
1967
388
        context.tablet_path = _tablet_path;
1968
388
    }
1969
1970
388
    context.data_dir = data_dir();
1971
388
    context.enable_unique_key_merge_on_write = enable_unique_key_merge_on_write();
1972
1973
388
    context.encrypt_algorithm = tablet_meta()->encryption_algorithm();
1974
388
}
1975
1976
200
Status Tablet::create_rowset(const RowsetMetaSharedPtr& rowset_meta, RowsetSharedPtr* rowset) {
1977
200
    return RowsetFactory::create_rowset(_tablet_meta->tablet_schema(),
1978
200
                                        rowset_meta->is_local() ? _tablet_path : "", rowset_meta,
  Branch (1978:41): [True: 190, False: 10]
1979
200
                                        rowset);
1980
200
}
1981
1982
7
Status Tablet::cooldown(RowsetSharedPtr rowset) {
1983
7
    std::unique_lock schema_change_lock(_schema_change_lock, std::try_to_lock);
1984
7
    if (!schema_change_lock.owns_lock()) {
  Branch (1984:9): [True: 0, False: 7]
1985
0
        return Status::Error<TRY_LOCK_FAILED>("try schema_change_lock failed");
1986
0
    }
1987
    // Check executing serially with compaction task.
1988
7
    std::unique_lock base_compaction_lock(_base_compaction_lock, std::try_to_lock);
1989
7
    if (!base_compaction_lock.owns_lock()) {
  Branch (1989:9): [True: 0, False: 7]
1990
0
        return Status::Error<TRY_LOCK_FAILED>("try base_compaction_lock failed");
1991
0
    }
1992
7
    std::unique_lock cumu_compaction_lock(_cumulative_compaction_lock, std::try_to_lock);
1993
7
    if (!cumu_compaction_lock.owns_lock()) {
  Branch (1993:9): [True: 0, False: 7]
1994
0
        return Status::Error<TRY_LOCK_FAILED>("try cumu_compaction_lock failed");
1995
0
    }
1996
7
    std::shared_lock cooldown_conf_rlock(_cooldown_conf_lock);
1997
7
    if (_cooldown_conf.cooldown_replica_id <= 0) { // wait for FE to push cooldown conf
  Branch (1997:9): [True: 2, False: 5]
1998
2
        return Status::InternalError("invalid cooldown_replica_id");
1999
2
    }
2000
2001
5
    if (_cooldown_conf.cooldown_replica_id == replica_id()) {
  Branch (2001:9): [True: 5, False: 0]
2002
        // this replica is cooldown replica
2003
5
        RETURN_IF_ERROR(_cooldown_data(std::move(rowset)));
Line
Count
Source
637
5
    do {                                \
638
5
        Status _status_ = (stmt);       \
639
5
        if (UNLIKELY(!_status_.ok())) { \
Line
Count
Source
36
5
#define UNLIKELY(expr) __builtin_expect(!!(expr), 0)
  Branch (36:24): [True: 0, False: 5]
640
0
            return _status_;            \
641
0
        }                               \
642
5
    } while (false)
  Branch (642:14): [Folded - Ignored]
2004
5
    } else {
2005
0
        Status st = _follow_cooldowned_data();
2006
0
        if (UNLIKELY(!st.ok())) {
Line
Count
Source
36
0
#define UNLIKELY(expr) __builtin_expect(!!(expr), 0)
  Branch (36:24): [True: 0, False: 0]
2007
0
            _last_failed_follow_cooldown_time = time(nullptr);
2008
0
            return st;
2009
0
        }
2010
0
        _last_failed_follow_cooldown_time = 0;
2011
0
    }
2012
5
    return Status::OK();
2013
5
}
2014
2015
// hold SHARED `cooldown_conf_lock`
2016
5
Status Tablet::_cooldown_data(RowsetSharedPtr rowset) {
2017
5
    DCHECK(_cooldown_conf.cooldown_replica_id == replica_id());
2018
2019
5
    auto storage_resource = DORIS_TRY(get_resource_by_storage_policy_id(storage_policy_id()));
Line
Count
Source
716
5
    ({                                           \
717
5
        auto&& res = (stmt);                     \
718
5
        using T = std::decay_t<decltype(res)>;   \
719
5
        if (!res.has_value()) [[unlikely]] {     \
  Branch (719:13): [True: 0, False: 5]
720
0
            return std::forward<T>(res).error(); \
721
0
        }                                        \
722
5
        std::forward<T>(res).value();            \
723
5
    });
2020
5
    RowsetSharedPtr old_rowset = nullptr;
2021
2022
5
    if (rowset) {
  Branch (2022:9): [True: 0, False: 5]
2023
0
        const auto& rowset_id = rowset->rowset_id();
2024
0
        const auto& rowset_version = rowset->version();
2025
0
        std::shared_lock meta_rlock(_meta_lock);
2026
0
        auto iter = _rs_version_map.find(rowset_version);
2027
0
        if (iter != _rs_version_map.end() && iter->second->rowset_id() == rowset_id) {
  Branch (2027:13): [True: 0, False: 0]
  Branch (2027:13): [True: 0, False: 0]
  Branch (2027:46): [True: 0, False: 0]
2028
0
            old_rowset = rowset;
2029
0
        }
2030
0
    }
2031
2032
5
    if (!old_rowset) {
  Branch (2032:9): [True: 5, False: 0]
2033
5
        old_rowset = pick_cooldown_rowset();
2034
5
    }
2035
2036
5
    if (!old_rowset) {
  Branch (2036:9): [True: 0, False: 5]
2037
0
        LOG(INFO) << "cannot pick cooldown rowset in tablet " << tablet_id();
2038
0
        return Status::OK();
2039
0
    }
2040
2041
5
    RowsetId new_rowset_id = _engine.next_rowset_id();
2042
5
    auto pending_rs_guard = _engine.pending_remote_rowsets().add(new_rowset_id);
2043
5
    Status st;
2044
5
    Defer defer {[&] {
2045
5
        if (!st.ok()) {
  Branch (2045:13): [True: 0, False: 5]
2046
            // reclaim the incomplete rowset data in remote storage
2047
0
            record_unused_remote_rowset(new_rowset_id, storage_resource.fs->id(),
2048
0
                                        old_rowset->num_segments());
2049
0
        }
2050
5
    }};
2051
5
    auto start = std::chrono::steady_clock::now();
2052
5
    if (st = old_rowset->upload_to(storage_resource, new_rowset_id); !st.ok()) {
  Branch (2052:70): [True: 0, False: 5]
2053
0
        return st;
2054
0
    }
2055
2056
5
    auto duration = std::chrono::duration<float>(std::chrono::steady_clock::now() - start);
2057
5
    LOG(INFO) << "Upload rowset " << old_rowset->version() << " " << new_rowset_id.to_string()
2058
5
              << " to " << storage_resource.fs->root_path().native()
2059
5
              << ", tablet_id=" << tablet_id() << ", duration=" << duration.count()
2060
5
              << ", capacity=" << old_rowset->total_disk_size()
2061
5
              << ", tp=" << old_rowset->total_disk_size() / duration.count()
2062
5
              << ", old rowset_id=" << old_rowset->rowset_id().to_string();
2063
2064
    // gen a new rowset
2065
5
    auto new_rowset_meta = std::make_shared<RowsetMeta>();
2066
5
    new_rowset_meta->init(old_rowset->rowset_meta().get());
2067
5
    new_rowset_meta->set_rowset_id(new_rowset_id);
2068
5
    new_rowset_meta->set_remote_storage_resource(std::move(storage_resource));
2069
5
    new_rowset_meta->set_creation_time(time(nullptr));
2070
5
    UniqueId cooldown_meta_id = UniqueId::gen_uid();
2071
5
    RowsetSharedPtr new_rowset;
2072
5
    RETURN_IF_ERROR(RowsetFactory::create_rowset(_tablet_meta->tablet_schema(), "", new_rowset_meta,
Line
Count
Source
637
5
    do {                                \
638
5
        Status _status_ = (stmt);       \
639
5
        if (UNLIKELY(!_status_.ok())) { \
Line
Count
Source
36
5
#define UNLIKELY(expr) __builtin_expect(!!(expr), 0)
  Branch (36:24): [True: 0, False: 5]
640
0
            return _status_;            \
641
0
        }                               \
642
5
    } while (false)
  Branch (642:14): [Folded - Ignored]
2073
5
                                                 &new_rowset));
2074
2075
5
    {
2076
5
        std::unique_lock meta_wlock(_meta_lock);
2077
5
        SCOPED_SIMPLE_TRACE_IF_TIMEOUT(TRACE_TABLET_LOCK_THRESHOLD);
Line
Count
Source
31
5
    SCOPED_SIMPLE_TRACE_TO_STREAM_IF_TIMEOUT(timeout, LOG(WARNING))
Line
Count
Source
41
5
    using namespace std::chrono_literals;                                               \
42
5
    auto VARNAME_LINENUM(scoped_simple_trace) = doris::MonotonicMicros();               \
43
5
    SCOPED_CLEANUP({                                                                    \
Line
Count
Source
34
5
    auto VARNAME_LINENUM(scoped_cleanup) = MakeScopedCleanup([&] { func_body });
44
5
        auto VARNAME_LINENUM(timeout_us) =                                              \
45
5
                std::chrono::duration_cast<std::chrono::microseconds>(timeout).count(); \
46
5
        auto VARNAME_LINENUM(cost_us) =                                                 \
47
5
                doris::MonotonicMicros() - VARNAME_LINENUM(scoped_simple_trace);        \
48
5
        if (VARNAME_LINENUM(cost_us) >= VARNAME_LINENUM(timeout_us)) {                  \
49
5
            stream << "Simple trace cost(us): " << VARNAME_LINENUM(cost_us);            \
50
5
        }                                                                               \
51
5
    })
2078
5
        if (tablet_state() == TABLET_RUNNING) {
  Branch (2078:13): [True: 5, False: 0]
2079
5
            RETURN_IF_ERROR(delete_rowsets({std::move(old_rowset)}, false));
Line
Count
Source
637
5
    do {                                \
638
5
        Status _status_ = (stmt);       \
639
5
        if (UNLIKELY(!_status_.ok())) { \
Line
Count
Source
36
5
#define UNLIKELY(expr) __builtin_expect(!!(expr), 0)
  Branch (36:24): [True: 0, False: 5]
640
0
            return _status_;            \
641
0
        }                               \
642
5
    } while (false)
  Branch (642:14): [Folded - Ignored]
2080
5
            add_rowsets({std::move(new_rowset)});
2081
            // TODO(plat1ko): process primary key
2082
5
            _tablet_meta->set_cooldown_meta_id(cooldown_meta_id);
2083
5
        }
2084
5
    }
2085
5
    {
2086
5
        std::shared_lock meta_rlock(_meta_lock);
2087
5
        SCOPED_SIMPLE_TRACE_IF_TIMEOUT(TRACE_TABLET_LOCK_THRESHOLD);
Line
Count
Source
31
5
    SCOPED_SIMPLE_TRACE_TO_STREAM_IF_TIMEOUT(timeout, LOG(WARNING))
Line
Count
Source
41
5
    using namespace std::chrono_literals;                                               \
42
5
    auto VARNAME_LINENUM(scoped_simple_trace) = doris::MonotonicMicros();               \
43
5
    SCOPED_CLEANUP({                                                                    \
Line
Count
Source
34
5
    auto VARNAME_LINENUM(scoped_cleanup) = MakeScopedCleanup([&] { func_body });
44
5
        auto VARNAME_LINENUM(timeout_us) =                                              \
45
5
                std::chrono::duration_cast<std::chrono::microseconds>(timeout).count(); \
46
5
        auto VARNAME_LINENUM(cost_us) =                                                 \
47
5
                doris::MonotonicMicros() - VARNAME_LINENUM(scoped_simple_trace);        \
48
5
        if (VARNAME_LINENUM(cost_us) >= VARNAME_LINENUM(timeout_us)) {                  \
49
5
            stream << "Simple trace cost(us): " << VARNAME_LINENUM(cost_us);            \
50
5
        }                                                                               \
51
5
    })
2088
5
        save_meta();
2089
5
    }
2090
    // Upload cooldowned rowset meta to remote fs
2091
    // ATTN: Even if it is an empty rowset, in order for the followers to synchronize, the coolown meta must be
2092
    // uploaded, otherwise followers may never completely cooldown.
2093
5
    if (auto t = _engine.tablet_manager()->get_tablet(tablet_id());
2094
5
        t != nullptr) { // `t` can be nullptr if it has been dropped
  Branch (2094:9): [True: 5, False: 0]
2095
5
        async_write_cooldown_meta(std::move(t));
2096
5
    }
2097
5
    return Status::OK();
2098
5
}
2099
2100
// hold SHARED `cooldown_conf_lock`
2101
Status Tablet::_read_cooldown_meta(const StorageResource& storage_resource,
2102
0
                                   TabletMetaPB* tablet_meta_pb) {
2103
0
    std::string remote_meta_path = storage_resource.cooldown_tablet_meta_path(
2104
0
            tablet_id(), _cooldown_conf.cooldown_replica_id, _cooldown_conf.term);
2105
0
    io::FileReaderSPtr tablet_meta_reader;
2106
0
    RETURN_IF_ERROR(storage_resource.fs->open_file(remote_meta_path, &tablet_meta_reader));
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]
2107
0
    auto file_size = tablet_meta_reader->size();
2108
0
    size_t bytes_read;
2109
0
    auto buf = std::unique_ptr<uint8_t[]>(new uint8_t[file_size]);
2110
0
    RETURN_IF_ERROR(tablet_meta_reader->read_at(0, {buf.get(), file_size}, &bytes_read));
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]
2111
0
    RETURN_IF_ERROR(tablet_meta_reader->close());
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]
2112
0
    if (!tablet_meta_pb->ParseFromArray(buf.get(), file_size)) {
  Branch (2112:9): [True: 0, False: 0]
2113
0
        return Status::InternalError("malformed tablet meta, path={}/{}",
2114
0
                                     storage_resource.fs->root_path().native(), remote_meta_path);
2115
0
    }
2116
0
    return Status::OK();
2117
0
}
2118
2119
// `rs_metas` MUST already be sorted by `RowsetMeta::comparator`
2120
5
Status check_version_continuity(const std::vector<RowsetMetaSharedPtr>& rs_metas) {
2121
5
    if (rs_metas.size() < 2) {
  Branch (2121:9): [True: 2, False: 3]
2122
2
        return Status::OK();
2123
2
    }
2124
3
    auto prev = rs_metas.begin();
2125
7
    for (auto it = rs_metas.begin() + 1; it != rs_metas.end(); ++it) {
  Branch (2125:42): [True: 4, False: 3]
2126
4
        if ((*prev)->end_version() + 1 != (*it)->start_version()) {
  Branch (2126:13): [True: 0, False: 4]
2127
0
            return Status::InternalError("versions are not continuity: prev={} cur={}",
2128
0
                                         (*prev)->version().to_string(),
2129
0
                                         (*it)->version().to_string());
2130
0
        }
2131
4
        prev = it;
2132
4
    }
2133
3
    return Status::OK();
2134
3
}
2135
2136
// It's guaranteed the write cooldown meta task would be invoked at the end unless BE crashes
2137
// one tablet would at most have one async task to be done
2138
5
void Tablet::async_write_cooldown_meta(TabletSharedPtr tablet) {
2139
5
    ExecEnv::GetInstance()->write_cooldown_meta_executors()->submit(std::move(tablet));
2140
5
}
2141
2142
2
bool Tablet::update_cooldown_conf(int64_t cooldown_term, int64_t cooldown_replica_id) {
2143
2
    std::unique_lock wlock(_cooldown_conf_lock, std::try_to_lock);
2144
2
    if (!wlock.owns_lock()) {
  Branch (2144:9): [True: 0, False: 2]
2145
0
        LOG(INFO) << "try cooldown_conf_lock failed, tablet_id=" << tablet_id();
2146
0
        return false;
2147
0
    }
2148
2
    if (cooldown_term <= _cooldown_conf.term) {
  Branch (2148:9): [True: 0, False: 2]
2149
0
        return false;
2150
0
    }
2151
2
    LOG(INFO) << "update cooldown conf. tablet_id=" << tablet_id()
2152
2
              << " cooldown_replica_id: " << _cooldown_conf.cooldown_replica_id << " -> "
2153
2
              << cooldown_replica_id << ", cooldown_term: " << _cooldown_conf.term << " -> "
2154
2
              << cooldown_term;
2155
2
    _cooldown_conf.cooldown_replica_id = cooldown_replica_id;
2156
2
    _cooldown_conf.term = cooldown_term;
2157
2
    return true;
2158
2
}
2159
2160
5
Status Tablet::write_cooldown_meta() {
2161
5
    std::shared_lock rlock(_cooldown_conf_lock);
2162
5
    if (_cooldown_conf.cooldown_replica_id != _tablet_meta->replica_id()) {
  Branch (2162:9): [True: 0, False: 5]
2163
0
        return Status::Aborted<false>("not cooldown replica({} vs {}) tablet_id={}",
2164
0
                                      _tablet_meta->replica_id(),
2165
0
                                      _cooldown_conf.cooldown_replica_id, tablet_id());
2166
0
    }
2167
2168
5
    auto storage_resource = DORIS_TRY(get_resource_by_storage_policy_id(storage_policy_id()));
Line
Count
Source
716
5
    ({                                           \
717
5
        auto&& res = (stmt);                     \
718
5
        using T = std::decay_t<decltype(res)>;   \
719
5
        if (!res.has_value()) [[unlikely]] {     \
  Branch (719:13): [True: 0, False: 5]
720
0
            return std::forward<T>(res).error(); \
721
0
        }                                        \
722
5
        std::forward<T>(res).value();            \
723
5
    });
2169
2170
5
    std::vector<RowsetMetaSharedPtr> cooldowned_rs_metas;
2171
5
    UniqueId cooldown_meta_id;
2172
5
    {
2173
5
        std::shared_lock meta_rlock(_meta_lock);
2174
11
        for (auto& rs_meta : _tablet_meta->all_rs_metas()) {
  Branch (2174:28): [True: 11, False: 5]
2175
11
            if (!rs_meta->is_local()) {
  Branch (2175:17): [True: 9, False: 2]
2176
9
                cooldowned_rs_metas.push_back(rs_meta);
2177
9
            }
2178
11
        }
2179
5
        cooldown_meta_id = _tablet_meta->cooldown_meta_id();
2180
5
    }
2181
5
    if (cooldowned_rs_metas.empty()) {
  Branch (2181:9): [True: 0, False: 5]
2182
0
        LOG(INFO) << "no cooldown meta to write, tablet_id=" << tablet_id();
2183
0
        return Status::OK();
2184
0
    }
2185
5
    std::sort(cooldowned_rs_metas.begin(), cooldowned_rs_metas.end(), RowsetMeta::comparator);
2186
5
    DCHECK(cooldowned_rs_metas.front()->start_version() == 0);
2187
    // If version not continuous, it must be a bug
2188
5
    if (auto st = check_version_continuity(cooldowned_rs_metas); !st.ok()) {
  Branch (2188:66): [True: 0, False: 5]
2189
0
        DCHECK(st.ok()) << st << " tablet_id=" << tablet_id();
2190
0
        st.set_code(ABORTED);
2191
0
        return st;
2192
0
    }
2193
2194
5
    TabletMetaPB tablet_meta_pb;
2195
5
    auto* rs_metas = tablet_meta_pb.mutable_rs_metas();
2196
5
    rs_metas->Reserve(cooldowned_rs_metas.size());
2197
9
    for (auto& rs_meta : cooldowned_rs_metas) {
  Branch (2197:24): [True: 9, False: 5]
2198
9
        rs_metas->Add(rs_meta->get_rowset_pb());
2199
9
    }
2200
5
    tablet_meta_pb.mutable_cooldown_meta_id()->set_hi(cooldown_meta_id.hi);
2201
5
    tablet_meta_pb.mutable_cooldown_meta_id()->set_lo(cooldown_meta_id.lo);
2202
2203
5
    std::string remote_meta_path = storage_resource.cooldown_tablet_meta_path(
2204
5
            tablet_id(), _cooldown_conf.cooldown_replica_id, _cooldown_conf.term);
2205
5
    io::FileWriterPtr tablet_meta_writer;
2206
    // FIXME(plat1ko): What if object store permanently unavailable?
2207
5
    RETURN_IF_ERROR(storage_resource.fs->create_file(remote_meta_path, &tablet_meta_writer));
Line
Count
Source
637
5
    do {                                \
638
5
        Status _status_ = (stmt);       \
639
5
        if (UNLIKELY(!_status_.ok())) { \
Line
Count
Source
36
5
#define UNLIKELY(expr) __builtin_expect(!!(expr), 0)
  Branch (36:24): [True: 0, False: 5]
640
0
            return _status_;            \
641
0
        }                               \
642
5
    } while (false)
  Branch (642:14): [Folded - Ignored]
2208
5
    auto val = tablet_meta_pb.SerializeAsString();
2209
5
    RETURN_IF_ERROR(tablet_meta_writer->append({val.data(), val.size()}));
Line
Count
Source
637
5
    do {                                \
638
5
        Status _status_ = (stmt);       \
639
5
        if (UNLIKELY(!_status_.ok())) { \
Line
Count
Source
36
5
#define UNLIKELY(expr) __builtin_expect(!!(expr), 0)
  Branch (36:24): [True: 0, False: 5]
640
0
            return _status_;            \
641
0
        }                               \
642
5
    } while (false)
  Branch (642:14): [Folded - Ignored]
2210
5
    return tablet_meta_writer->close();
2211
5
}
2212
2213
// hold SHARED `cooldown_conf_lock`
2214
0
Status Tablet::_follow_cooldowned_data() {
2215
0
    DCHECK(_cooldown_conf.cooldown_replica_id != replica_id());
2216
0
    LOG(INFO) << "try to follow cooldowned data. tablet_id=" << tablet_id()
2217
0
              << " cooldown_replica_id=" << _cooldown_conf.cooldown_replica_id
2218
0
              << " local replica=" << replica_id();
2219
2220
0
    auto storage_resource = DORIS_TRY(get_resource_by_storage_policy_id(storage_policy_id()));
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
    });
2221
    // MUST executing serially with cold data compaction, because compaction input rowsets may be deleted by this function
2222
0
    std::unique_lock cold_compaction_lock(_cold_compaction_lock, std::try_to_lock);
2223
0
    if (!cold_compaction_lock.owns_lock()) {
  Branch (2223:9): [True: 0, False: 0]
2224
0
        return Status::Error<TRY_LOCK_FAILED>("try cold_compaction_lock failed");
2225
0
    }
2226
2227
0
    TabletMetaPB cooldown_meta_pb;
2228
0
    auto st = _read_cooldown_meta(storage_resource, &cooldown_meta_pb);
2229
0
    if (!st.ok()) {
  Branch (2229:9): [True: 0, False: 0]
2230
0
        LOG(INFO) << "cannot read cooldown meta: " << st;
2231
0
        return Status::InternalError<false>("cannot read cooldown meta");
2232
0
    }
2233
0
    DCHECK(cooldown_meta_pb.rs_metas_size() > 0);
2234
0
    if (_tablet_meta->cooldown_meta_id() == cooldown_meta_pb.cooldown_meta_id()) {
  Branch (2234:9): [True: 0, False: 0]
2235
        // cooldowned rowsets are same, no need to follow
2236
0
        return Status::OK();
2237
0
    }
2238
2239
0
    int64_t cooldowned_version = cooldown_meta_pb.rs_metas().rbegin()->end_version();
2240
2241
0
    std::vector<RowsetSharedPtr> overlap_rowsets;
2242
0
    bool version_aligned = false;
2243
2244
    // Holding these to delete rowsets' shared ptr until save meta can avoid trash sweeping thread
2245
    // deleting these rowsets' files before rowset meta has been removed from disk, which may cause
2246
    // data loss when BE reboot before save meta to disk.
2247
0
    std::vector<RowsetSharedPtr> to_delete;
2248
0
    std::vector<RowsetSharedPtr> to_add;
2249
2250
0
    {
2251
0
        std::lock_guard wlock(_meta_lock);
2252
0
        SCOPED_SIMPLE_TRACE_IF_TIMEOUT(TRACE_TABLET_LOCK_THRESHOLD);
Line
Count
Source
31
0
    SCOPED_SIMPLE_TRACE_TO_STREAM_IF_TIMEOUT(timeout, LOG(WARNING))
Line
Count
Source
41
0
    using namespace std::chrono_literals;                                               \
42
0
    auto VARNAME_LINENUM(scoped_simple_trace) = doris::MonotonicMicros();               \
43
0
    SCOPED_CLEANUP({                                                                    \
Line
Count
Source
34
0
    auto VARNAME_LINENUM(scoped_cleanup) = MakeScopedCleanup([&] { func_body });
44
0
        auto VARNAME_LINENUM(timeout_us) =                                              \
45
0
                std::chrono::duration_cast<std::chrono::microseconds>(timeout).count(); \
46
0
        auto VARNAME_LINENUM(cost_us) =                                                 \
47
0
                doris::MonotonicMicros() - VARNAME_LINENUM(scoped_simple_trace);        \
48
0
        if (VARNAME_LINENUM(cost_us) >= VARNAME_LINENUM(timeout_us)) {                  \
49
0
            stream << "Simple trace cost(us): " << VARNAME_LINENUM(cost_us);            \
50
0
        }                                                                               \
51
0
    })
2253
0
        if (tablet_state() != TABLET_RUNNING) {
  Branch (2253:13): [True: 0, False: 0]
2254
0
            return Status::InternalError<false>("tablet not running");
2255
0
        }
2256
2257
0
        for (auto& [v, rs] : _rs_version_map) {
  Branch (2257:28): [True: 0, False: 0]
2258
0
            if (v.second <= cooldowned_version) {
  Branch (2258:17): [True: 0, False: 0]
2259
0
                overlap_rowsets.push_back(rs);
2260
0
                if (!version_aligned && v.second == cooldowned_version) {
  Branch (2260:21): [True: 0, False: 0]
  Branch (2260:41): [True: 0, False: 0]
2261
0
                    version_aligned = true;
2262
0
                }
2263
0
            } else if (!rs->is_local()) {
  Branch (2263:24): [True: 0, False: 0]
2264
0
                return Status::InternalError<false>(
2265
0
                        "cooldowned version larger than that to follow with cooldown version {}",
2266
0
                        cooldowned_version);
2267
0
            }
2268
0
        }
2269
2270
0
        if (!version_aligned) {
  Branch (2270:13): [True: 0, False: 0]
2271
0
            return Status::InternalError<false>("cooldowned version is not aligned with version {}",
2272
0
                                                cooldowned_version);
2273
0
        }
2274
2275
0
        std::sort(overlap_rowsets.begin(), overlap_rowsets.end(), Rowset::comparator);
2276
2277
        // Find different rowset in `overlap_rowsets` and `cooldown_meta_pb.rs_metas`
2278
0
        auto rs_pb_it = cooldown_meta_pb.rs_metas().begin();
2279
0
        auto rs_it = overlap_rowsets.begin();
2280
0
        for (; rs_pb_it != cooldown_meta_pb.rs_metas().end() && rs_it != overlap_rowsets.end();
  Branch (2280:16): [True: 0, False: 0]
  Branch (2280:16): [True: 0, False: 0]
  Branch (2280:65): [True: 0, False: 0]
2281
0
             ++rs_pb_it, ++rs_it) {
2282
0
            if (rs_pb_it->rowset_id_v2() != (*rs_it)->rowset_id().to_string()) {
  Branch (2282:17): [True: 0, False: 0]
2283
0
                break;
2284
0
            }
2285
0
        }
2286
2287
0
        to_delete.assign(rs_it, overlap_rowsets.end());
2288
0
        to_add.reserve(cooldown_meta_pb.rs_metas().end() - rs_pb_it);
2289
0
        for (; rs_pb_it != cooldown_meta_pb.rs_metas().end(); ++rs_pb_it) {
  Branch (2289:16): [True: 0, False: 0]
2290
0
            auto rs_meta = std::make_shared<RowsetMeta>();
2291
0
            rs_meta->init_from_pb(*rs_pb_it);
2292
0
            RowsetSharedPtr rs;
2293
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]
2294
0
                    RowsetFactory::create_rowset(_tablet_meta->tablet_schema(), "", rs_meta, &rs));
2295
0
            to_add.push_back(std::move(rs));
2296
0
        }
2297
        // Note: We CANNOT call `modify_rowsets` here because `modify_rowsets` cannot process version graph correctly.
2298
0
        RETURN_IF_ERROR(delete_rowsets(to_delete, false));
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]
2299
0
        add_rowsets(to_add);
2300
        // TODO(plat1ko): process primary key
2301
0
        _tablet_meta->set_cooldown_meta_id(cooldown_meta_pb.cooldown_meta_id());
2302
0
    }
2303
2304
0
    {
2305
0
        std::lock_guard rlock(_meta_lock);
2306
0
        SCOPED_SIMPLE_TRACE_IF_TIMEOUT(TRACE_TABLET_LOCK_THRESHOLD);
Line
Count
Source
31
0
    SCOPED_SIMPLE_TRACE_TO_STREAM_IF_TIMEOUT(timeout, LOG(WARNING))
Line
Count
Source
41
0
    using namespace std::chrono_literals;                                               \
42
0
    auto VARNAME_LINENUM(scoped_simple_trace) = doris::MonotonicMicros();               \
43
0
    SCOPED_CLEANUP({                                                                    \
Line
Count
Source
34
0
    auto VARNAME_LINENUM(scoped_cleanup) = MakeScopedCleanup([&] { func_body });
44
0
        auto VARNAME_LINENUM(timeout_us) =                                              \
45
0
                std::chrono::duration_cast<std::chrono::microseconds>(timeout).count(); \
46
0
        auto VARNAME_LINENUM(cost_us) =                                                 \
47
0
                doris::MonotonicMicros() - VARNAME_LINENUM(scoped_simple_trace);        \
48
0
        if (VARNAME_LINENUM(cost_us) >= VARNAME_LINENUM(timeout_us)) {                  \
49
0
            stream << "Simple trace cost(us): " << VARNAME_LINENUM(cost_us);            \
50
0
        }                                                                               \
51
0
    })
2307
0
        save_meta();
2308
0
    }
2309
2310
0
    if (!to_add.empty()) {
  Branch (2310:9): [True: 0, False: 0]
2311
0
        LOG(INFO) << "modify rowsets when follow cooldowned data, tablet_id=" << tablet_id()
2312
0
                  << [&]() {
2313
0
                         std::stringstream ss;
2314
0
                         ss << " delete rowsets:\n";
2315
0
                         for (auto&& rs : to_delete) {
  Branch (2315:41): [True: 0, False: 0]
2316
0
                             ss << rs->version() << ' ' << rs->rowset_id() << '\n';
2317
0
                         }
2318
0
                         ss << "add rowsets:\n";
2319
0
                         for (auto&& rs : to_add) {
  Branch (2319:41): [True: 0, False: 0]
2320
0
                             ss << rs->version() << ' ' << rs->rowset_id() << '\n';
2321
0
                         }
2322
0
                         return ss.str();
2323
0
                     }();
2324
0
    }
2325
2326
0
    return Status::OK();
2327
0
}
2328
2329
10
bool Tablet::_has_data_to_cooldown() {
2330
10
    int64_t min_local_version = std::numeric_limits<int64_t>::max();
2331
10
    RowsetSharedPtr rowset;
2332
10
    std::shared_lock meta_rlock(_meta_lock);
2333
    // Ususally once the tablet has done cooldown successfully then the first
2334
    // rowset would always be remote rowset
2335
10
    bool has_cooldowned = false;
2336
29
    for (const auto& [_, rs] : _rs_version_map) {
  Branch (2336:30): [True: 29, False: 7]
2337
29
        if (!rs->is_local()) {
  Branch (2337:13): [True: 3, False: 26]
2338
3
            has_cooldowned = true;
2339
3
            break;
2340
3
        }
2341
29
    }
2342
32
    for (auto& [v, rs] : _rs_version_map) {
  Branch (2342:24): [True: 32, False: 10]
2343
32
        auto predicate = rs->is_local() && v.first < min_local_version;
  Branch (2343:26): [True: 28, False: 4]
  Branch (2343:44): [True: 28, False: 0]
2344
32
        if (!has_cooldowned) {
  Branch (2344:13): [True: 25, False: 7]
2345
25
            predicate = predicate && (rs->data_disk_size() > 0);
  Branch (2345:25): [True: 25, False: 0]
  Branch (2345:38): [True: 22, False: 3]
2346
25
        }
2347
32
        if (predicate) {
  Branch (2347:13): [True: 25, False: 7]
2348
            // this is a local rowset and has data
2349
25
            min_local_version = v.first;
2350
25
            rowset = rs;
2351
25
        }
2352
32
    }
2353
2354
10
    int64_t newest_cooldown_time = 0;
2355
10
    if (rowset != nullptr) {
  Branch (2355:9): [True: 9, False: 1]
2356
9
        newest_cooldown_time = _get_newest_cooldown_time(rowset);
2357
9
    }
2358
2359
10
    return (newest_cooldown_time != 0) && (newest_cooldown_time < UnixSeconds());
  Branch (2359:12): [True: 9, False: 1]
  Branch (2359:43): [True: 8, False: 1]
2360
10
}
2361
2362
9
RowsetSharedPtr Tablet::pick_cooldown_rowset() {
2363
9
    RowsetSharedPtr rowset;
2364
2365
9
    if (!_has_data_to_cooldown()) {
  Branch (2365:9): [True: 1, False: 8]
2366
1
        return nullptr;
2367
1
    }
2368
2369
    // TODO(plat1ko): should we maintain `cooldowned_version` in `Tablet`?
2370
8
    int64_t cooldowned_version = -1;
2371
    // We pick the rowset with smallest start version in local.
2372
8
    int64_t min_local_version = std::numeric_limits<int64_t>::max();
2373
8
    {
2374
8
        std::shared_lock meta_rlock(_meta_lock);
2375
26
        for (auto& [v, rs] : _rs_version_map) {
  Branch (2375:28): [True: 26, False: 8]
2376
26
            if (!rs->is_local()) {
  Branch (2376:17): [True: 4, False: 22]
2377
4
                cooldowned_version = std::max(cooldowned_version, v.second);
2378
22
            } else if (v.first < min_local_version) { // this is a local rowset
  Branch (2378:24): [True: 22, False: 0]
2379
22
                min_local_version = v.first;
2380
22
                rowset = rs;
2381
22
            }
2382
26
        }
2383
8
    }
2384
8
    if (!rowset) {
  Branch (2384:9): [True: 0, False: 8]
2385
0
        return nullptr;
2386
0
    }
2387
8
    if (tablet_footprint() == 0) {
  Branch (2387:9): [True: 0, False: 8]
2388
0
        VLOG_DEBUG << "skip cooldown due to empty tablet_id = " << tablet_id();
Line
Count
Source
41
0
#define VLOG_DEBUG VLOG(7)
2389
0
        return nullptr;
2390
0
    }
2391
8
    if (min_local_version != cooldowned_version + 1) { // ensure version continuity
  Branch (2391:9): [True: 0, False: 8]
2392
0
        if (UNLIKELY(cooldowned_version != -1)) {
Line
Count
Source
36
0
#define UNLIKELY(expr) __builtin_expect(!!(expr), 0)
  Branch (36:24): [True: 0, False: 0]
2393
0
            LOG(WARNING) << "version not continuous. tablet_id=" << tablet_id()
2394
0
                         << " cooldowned_version=" << cooldowned_version
2395
0
                         << " min_local_version=" << min_local_version;
2396
0
        }
2397
0
        return nullptr;
2398
0
    }
2399
8
    return rowset;
2400
8
}
2401
2402
12
int64_t Tablet::_get_newest_cooldown_time(const RowsetSharedPtr& rowset) {
2403
12
    int64_t id = storage_policy_id();
2404
12
    if (id <= 0) {
  Branch (2404:9): [True: 0, False: 12]
2405
0
        VLOG_DEBUG << "tablet does not need cooldown, tablet id: " << tablet_id();
Line
Count
Source
41
0
#define VLOG_DEBUG VLOG(7)
2406
0
        return 0;
2407
0
    }
2408
12
    auto storage_policy = get_storage_policy(id);
2409
12
    if (!storage_policy) {
  Branch (2409:9): [True: 0, False: 12]
2410
0
        LOG(WARNING) << "Cannot get storage policy: " << id;
2411
0
        return 0;
2412
0
    }
2413
12
    auto cooldown_ttl_sec = storage_policy->cooldown_ttl;
2414
12
    auto cooldown_datetime = storage_policy->cooldown_datetime;
2415
12
    int64_t newest_cooldown_time = std::numeric_limits<int64_t>::max();
2416
2417
12
    if (cooldown_ttl_sec >= 0) {
  Branch (2417:9): [True: 9, False: 3]
2418
9
        newest_cooldown_time = rowset->newest_write_timestamp() + cooldown_ttl_sec;
2419
9
    }
2420
12
    if (cooldown_datetime > 0) {
  Branch (2420:9): [True: 10, False: 2]
2421
10
        newest_cooldown_time = std::min(newest_cooldown_time, cooldown_datetime);
2422
10
    }
2423
2424
12
    return newest_cooldown_time;
2425
12
}
2426
2427
4
RowsetSharedPtr Tablet::need_cooldown(int64_t* cooldown_timestamp, size_t* file_size) {
2428
4
    RowsetSharedPtr rowset = pick_cooldown_rowset();
2429
4
    if (!rowset) {
  Branch (2429:9): [True: 1, False: 3]
2430
1
        VLOG_DEBUG << "pick cooldown rowset, get null, tablet id: " << tablet_id();
Line
Count
Source
41
0
#define VLOG_DEBUG VLOG(7)
2431
1
        return nullptr;
2432
1
    }
2433
2434
3
    auto newest_cooldown_time = _get_newest_cooldown_time(rowset);
2435
2436
    // the rowset should do cooldown job only if it's cooldown ttl plus newest write time is less than
2437
    // current time or it's datatime is less than current time
2438
3
    if (newest_cooldown_time != 0 && newest_cooldown_time < UnixSeconds()) {
  Branch (2438:9): [True: 3, False: 0]
  Branch (2438:38): [True: 3, False: 0]
2439
3
        *cooldown_timestamp = newest_cooldown_time;
2440
3
        *file_size = rowset->total_disk_size();
2441
3
        VLOG_DEBUG << "tablet need cooldown, tablet id: " << tablet_id()
Line
Count
Source
41
0
#define VLOG_DEBUG VLOG(7)
2442
0
                   << " file_size: " << *file_size;
2443
3
        return rowset;
2444
3
    }
2445
2446
0
    VLOG_DEBUG << "tablet does not need cooldown, tablet id: " << tablet_id()
Line
Count
Source
41
0
#define VLOG_DEBUG VLOG(7)
2447
0
               << " newest write time: " << rowset->newest_write_timestamp();
2448
0
    return nullptr;
2449
3
}
2450
2451
void Tablet::record_unused_remote_rowset(const RowsetId& rowset_id, const std::string& resource,
2452
0
                                         int64_t num_segments) {
2453
0
    auto gc_key = REMOTE_ROWSET_GC_PREFIX + rowset_id.to_string();
2454
0
    RemoteRowsetGcPB gc_pb;
2455
0
    gc_pb.set_resource_id(resource);
2456
0
    gc_pb.set_tablet_id(tablet_id());
2457
0
    gc_pb.set_num_segments(num_segments);
2458
0
    auto st =
2459
0
            _data_dir->get_meta()->put(META_COLUMN_FAMILY_INDEX, gc_key, gc_pb.SerializeAsString());
2460
0
    if (!st.ok()) {
  Branch (2460:9): [True: 0, False: 0]
2461
0
        LOG(WARNING) << "failed to record unused remote rowset. tablet_id=" << tablet_id()
2462
0
                     << " rowset_id=" << rowset_id << " resource_id=" << resource;
2463
0
    }
2464
0
    unused_remote_rowset_num << 1;
2465
0
}
2466
2467
0
Status Tablet::remove_all_remote_rowsets() {
2468
0
    DCHECK(tablet_state() == TABLET_SHUTDOWN);
2469
0
    std::set<std::string> resource_ids;
2470
0
    for (auto& rs_meta : _tablet_meta->all_rs_metas()) {
  Branch (2470:24): [True: 0, False: 0]
2471
0
        if (!rs_meta->is_local()) {
  Branch (2471:13): [True: 0, False: 0]
2472
0
            resource_ids.insert(rs_meta->resource_id());
2473
0
        }
2474
0
    }
2475
0
    if (resource_ids.empty()) {
  Branch (2475:9): [True: 0, False: 0]
2476
0
        return Status::OK();
2477
0
    }
2478
0
    auto tablet_gc_key = REMOTE_TABLET_GC_PREFIX + std::to_string(tablet_id());
2479
0
    RemoteTabletGcPB gc_pb;
2480
0
    for (auto& resource_id : resource_ids) {
  Branch (2480:28): [True: 0, False: 0]
2481
0
        gc_pb.add_resource_ids(resource_id);
2482
0
    }
2483
0
    return _data_dir->get_meta()->put(META_COLUMN_FAMILY_INDEX, tablet_gc_key,
2484
0
                                      gc_pb.SerializeAsString());
2485
0
}
2486
2487
0
void Tablet::update_max_version_schema(const TabletSchemaSPtr& tablet_schema) {
2488
0
    std::lock_guard wrlock(_meta_lock);
2489
0
    SCOPED_SIMPLE_TRACE_IF_TIMEOUT(TRACE_TABLET_LOCK_THRESHOLD);
Line
Count
Source
31
0
    SCOPED_SIMPLE_TRACE_TO_STREAM_IF_TIMEOUT(timeout, LOG(WARNING))
Line
Count
Source
41
0
    using namespace std::chrono_literals;                                               \
42
0
    auto VARNAME_LINENUM(scoped_simple_trace) = doris::MonotonicMicros();               \
43
0
    SCOPED_CLEANUP({                                                                    \
Line
Count
Source
34
0
    auto VARNAME_LINENUM(scoped_cleanup) = MakeScopedCleanup([&] { func_body });
44
0
        auto VARNAME_LINENUM(timeout_us) =                                              \
45
0
                std::chrono::duration_cast<std::chrono::microseconds>(timeout).count(); \
46
0
        auto VARNAME_LINENUM(cost_us) =                                                 \
47
0
                doris::MonotonicMicros() - VARNAME_LINENUM(scoped_simple_trace);        \
48
0
        if (VARNAME_LINENUM(cost_us) >= VARNAME_LINENUM(timeout_us)) {                  \
49
0
            stream << "Simple trace cost(us): " << VARNAME_LINENUM(cost_us);            \
50
0
        }                                                                               \
51
0
    })
2490
    // Double Check for concurrent update
2491
0
    if (!_max_version_schema ||
  Branch (2491:9): [True: 0, False: 0]
2492
0
        tablet_schema->schema_version() > _max_version_schema->schema_version()) {
  Branch (2492:9): [True: 0, False: 0]
2493
0
        _max_version_schema = tablet_schema;
2494
0
    }
2495
0
}
2496
2497
0
CalcDeleteBitmapExecutor* Tablet::calc_delete_bitmap_executor() {
2498
0
    return _engine.calc_delete_bitmap_executor();
2499
0
}
2500
2501
Status Tablet::save_delete_bitmap(const TabletTxnInfo* txn_info, int64_t txn_id,
2502
                                  DeleteBitmapPtr delete_bitmap, RowsetWriter* rowset_writer,
2503
                                  const RowsetIdUnorderedSet& cur_rowset_ids,
2504
3
                                  int64_t next_visible_version) {
2505
3
    RowsetSharedPtr rowset = txn_info->rowset;
2506
3
    int64_t cur_version = rowset->start_version();
2507
2508
    // update version without write lock, compaction and publish_txn
2509
    // will update delete bitmap, handle compaction with _rowset_update_lock
2510
    // and publish_txn runs sequential so no need to lock here
2511
3
    for (auto& [key, bitmap] : delete_bitmap->delete_bitmap) {
  Branch (2511:30): [True: 3, False: 3]
2512
        // skip sentinel mark, which is used for delete bitmap correctness check
2513
3
        if (std::get<1>(key) != DeleteBitmap::INVALID_SEGMENT_ID) {
  Branch (2513:13): [True: 2, False: 1]
2514
2
            _tablet_meta->delete_bitmap()->merge({std::get<0>(key), std::get<1>(key), cur_version},
2515
2
                                                 bitmap);
2516
2
        }
2517
3
    }
2518
2519
3
    return Status::OK();
2520
3
}
2521
2522
0
void Tablet::merge_delete_bitmap(const DeleteBitmap& delete_bitmap) {
2523
0
    _tablet_meta->delete_bitmap()->merge(delete_bitmap);
2524
0
}
2525
2526
0
bool Tablet::check_all_rowset_segment() {
2527
0
    std::shared_lock rdlock(_meta_lock);
2528
0
    for (auto& version_rowset : _rs_version_map) {
  Branch (2528:31): [True: 0, False: 0]
2529
0
        RowsetSharedPtr rowset = version_rowset.second;
2530
0
        if (!rowset->check_rowset_segment()) {
  Branch (2530:13): [True: 0, False: 0]
2531
0
            LOG(WARNING) << "Tablet Segment Check. find a bad tablet, tablet_id=" << tablet_id();
2532
0
            return false;
2533
0
        }
2534
0
    }
2535
0
    return true;
2536
0
}
2537
2538
11
void Tablet::set_skip_compaction(bool skip, CompactionType compaction_type, int64_t start) {
2539
11
    if (!skip) {
  Branch (2539:9): [True: 0, False: 11]
2540
0
        _skip_cumu_compaction = false;
2541
0
        _skip_base_compaction = false;
2542
0
        return;
2543
0
    }
2544
11
    if (compaction_type == CompactionType::CUMULATIVE_COMPACTION) {
  Branch (2544:9): [True: 11, False: 0]
2545
11
        _skip_cumu_compaction = true;
2546
11
        _skip_cumu_compaction_ts = start;
2547
11
    } else {
2548
0
        DCHECK(compaction_type == CompactionType::BASE_COMPACTION);
2549
0
        _skip_base_compaction = true;
2550
0
        _skip_base_compaction_ts = start;
2551
0
    }
2552
11
}
2553
2554
257
bool Tablet::should_skip_compaction(CompactionType compaction_type, int64_t now) {
2555
257
    if (compaction_type == CompactionType::CUMULATIVE_COMPACTION && _skip_cumu_compaction &&
  Branch (2555:9): [True: 257, False: 0]
  Branch (2555:69): [True: 2, False: 255]
2556
257
        now < _skip_cumu_compaction_ts + config::skip_tablet_compaction_second) {
  Branch (2556:9): [True: 2, False: 0]
2557
2
        return true;
2558
255
    } else if (compaction_type == CompactionType::BASE_COMPACTION && _skip_base_compaction &&
  Branch (2558:16): [True: 0, False: 255]
  Branch (2558:70): [True: 0, False: 0]
2559
255
               now < _skip_base_compaction_ts + config::skip_tablet_compaction_second) {
  Branch (2559:16): [True: 0, False: 0]
2560
0
        return true;
2561
0
    }
2562
255
    return false;
2563
257
}
2564
2565
0
std::pair<std::string, int64_t> Tablet::get_binlog_info(std::string_view binlog_version) const {
2566
0
    return RowsetMetaManager::get_binlog_info(_data_dir->get_meta(), tablet_uid(), binlog_version);
2567
0
}
2568
2569
std::string Tablet::get_rowset_binlog_meta(std::string_view binlog_version,
2570
0
                                           std::string_view rowset_id) const {
2571
0
    return RowsetMetaManager::get_rowset_binlog_meta(_data_dir->get_meta(), tablet_uid(),
2572
0
                                                     binlog_version, rowset_id);
2573
0
}
2574
2575
Status Tablet::get_rowset_binlog_metas(const std::vector<int64_t>& binlog_versions,
2576
0
                                       RowsetBinlogMetasPB* metas_pb) {
2577
0
    return RowsetMetaManager::get_rowset_binlog_metas(_data_dir->get_meta(), tablet_uid(),
2578
0
                                                      binlog_versions, metas_pb);
2579
0
}
2580
2581
4
Status Tablet::get_rowset_binlog_metas(Version binlog_versions, RowsetBinlogMetasPB* metas_pb) {
2582
4
    return RowsetMetaManager::get_rowset_binlog_metas(_data_dir->get_meta(), tablet_uid(),
2583
4
                                                      binlog_versions, metas_pb);
2584
4
}
2585
2586
std::string Tablet::get_segment_filepath(std::string_view rowset_id,
2587
0
                                         std::string_view segment_index) const {
2588
0
    return fmt::format("{}/_binlog/{}_{}.dat", _tablet_path, rowset_id, segment_index);
2589
0
}
2590
2591
1
std::string Tablet::get_segment_filepath(std::string_view rowset_id, int64_t segment_index) const {
2592
1
    return fmt::format("{}/_binlog/{}_{}.dat", _tablet_path, rowset_id, segment_index);
2593
1
}
2594
2595
0
std::vector<std::string> Tablet::get_binlog_filepath(std::string_view binlog_version) const {
2596
0
    const auto& [rowset_id, num_segments] = get_binlog_info(binlog_version);
2597
0
    std::vector<std::string> binlog_filepath;
2598
0
    for (int i = 0; i < num_segments; ++i) {
  Branch (2598:21): [True: 0, False: 0]
2599
        // TODO(Drogon): rewrite by filesystem path
2600
0
        auto segment_file = fmt::format("{}_{}.dat", rowset_id, i);
2601
0
        binlog_filepath.emplace_back(fmt::format("{}/_binlog/{}", _tablet_path, segment_file));
2602
0
    }
2603
0
    return binlog_filepath;
2604
0
}
2605
2606
0
bool Tablet::can_add_binlog(uint64_t total_binlog_size) const {
2607
0
    return !_data_dir->reach_capacity_limit(total_binlog_size);
2608
0
}
2609
2610
14
bool Tablet::is_enable_binlog() {
2611
14
    return config::enable_feature_binlog && tablet_meta()->binlog_config().is_enable();
  Branch (2611:12): [True: 0, False: 14]
  Branch (2611:45): [True: 0, False: 0]
2612
14
}
2613
2614
0
void Tablet::set_binlog_config(BinlogConfig binlog_config) {
2615
0
    tablet_meta()->set_binlog_config(binlog_config);
2616
0
}
2617
2618
2
void Tablet::gc_binlogs(int64_t version) {
2619
2
    auto meta = _data_dir->get_meta();
2620
2
    DCHECK(meta != nullptr);
2621
2622
2
    const auto& tablet_uid = this->tablet_uid();
2623
2
    const auto tablet_id = this->tablet_id();
2624
2
    std::string begin_key = make_binlog_meta_key_prefix(tablet_uid);
2625
2
    std::string end_key = make_binlog_meta_key_prefix(tablet_uid, version + 1);
2626
2
    LOG(INFO) << fmt::format("gc binlog meta, tablet_id:{}, begin_key:{}, end_key:{}", tablet_id,
2627
2
                             begin_key, end_key);
2628
2629
2
    std::vector<std::string> wait_for_deleted_binlog_keys;
2630
2
    std::vector<std::string> wait_for_deleted_binlog_files;
2631
2
    auto add_to_wait_for_deleted = [&](std::string_view key, std::string_view rowset_id,
2632
2
                                       int64_t num_segments) {
2633
        // add binlog meta key and binlog data key
2634
1
        wait_for_deleted_binlog_keys.emplace_back(key);
2635
1
        wait_for_deleted_binlog_keys.push_back(get_binlog_data_key_from_meta_key(key));
2636
2637
        // add binlog segment files and index files
2638
2
        for (int64_t i = 0; i < num_segments; ++i) {
  Branch (2638:29): [True: 1, False: 1]
2639
1
            auto segment_file_path = get_segment_filepath(rowset_id, i);
2640
1
            wait_for_deleted_binlog_files.emplace_back(segment_file_path);
2641
2642
            // index files
2643
1
            if (tablet_schema()->has_inverted_index()) {
  Branch (2643:17): [True: 1, False: 0]
2644
1
                if (tablet_schema()->get_inverted_index_storage_format() ==
  Branch (2644:21): [True: 0, False: 1]
2645
1
                    InvertedIndexStorageFormatPB::V1) {
2646
0
                    for (const auto& index : tablet_schema()->inverted_indexes()) {
  Branch (2646:44): [True: 0, False: 0]
2647
0
                        auto index_file = InvertedIndexDescriptor::get_index_file_path_v1(
2648
0
                                InvertedIndexDescriptor::get_index_file_path_prefix(
2649
0
                                        segment_file_path),
2650
0
                                index->index_id(), index->get_index_suffix());
2651
0
                        wait_for_deleted_binlog_files.emplace_back(index_file);
2652
0
                    }
2653
1
                } else {
2654
1
                    auto index_file = InvertedIndexDescriptor::get_index_file_path_v2(
2655
1
                            InvertedIndexDescriptor::get_index_file_path_prefix(segment_file_path));
2656
1
                    wait_for_deleted_binlog_files.emplace_back(index_file);
2657
1
                }
2658
1
            }
2659
1
        }
2660
1
    };
2661
2662
2
    auto check_binlog_ttl = [&](std::string_view key, std::string_view value) mutable -> bool {
2663
2
        if (key >= end_key) {
  Branch (2663:13): [True: 1, False: 1]
2664
1
            return false;
2665
1
        }
2666
2667
1
        BinlogMetaEntryPB binlog_meta_entry_pb;
2668
1
        if (!binlog_meta_entry_pb.ParseFromArray(value.data(), value.size())) {
  Branch (2668:13): [True: 0, False: 1]
2669
0
            LOG(WARNING) << "failed to parse binlog meta entry, key:" << key;
2670
0
            return true;
2671
0
        }
2672
2673
1
        auto num_segments = binlog_meta_entry_pb.num_segments();
2674
1
        std::string rowset_id;
2675
1
        if (binlog_meta_entry_pb.has_rowset_id_v2()) {
  Branch (2675:13): [True: 1, False: 0]
2676
1
            rowset_id = binlog_meta_entry_pb.rowset_id_v2();
2677
1
        } else {
2678
            // key is 'binlog_meta_6943f1585fe834b5-e542c2b83a21d0b7_00000000000000000069_020000000000000135449d7cd7eadfe672aa0f928fa99593', extract last part '020000000000000135449d7cd7eadfe672aa0f928fa99593'
2679
0
            auto pos = key.rfind('_');
2680
0
            if (pos == std::string::npos) {
  Branch (2680:17): [True: 0, False: 0]
2681
0
                LOG(WARNING) << fmt::format("invalid binlog meta key:{}", key);
2682
0
                return false;
2683
0
            }
2684
0
            rowset_id = key.substr(pos + 1);
2685
0
        }
2686
1
        add_to_wait_for_deleted(key, rowset_id, num_segments);
2687
2688
1
        return true;
2689
1
    };
2690
2691
2
    auto status = meta->iterate(META_COLUMN_FAMILY_INDEX, begin_key, check_binlog_ttl);
2692
2
    if (!status.ok()) {
  Branch (2692:9): [True: 0, False: 2]
2693
0
        LOG(WARNING) << "failed to iterate binlog meta, status:" << status;
2694
0
        return;
2695
0
    }
2696
2697
    // first remove binlog files, if failed, just break, then retry next time
2698
    // this keep binlog meta in meta store, so that binlog can be removed next time
2699
2
    bool remove_binlog_files_failed = false;
2700
2
    for (auto& file : wait_for_deleted_binlog_files) {
  Branch (2700:21): [True: 2, False: 2]
2701
2
        if (unlink(file.c_str()) != 0) {
  Branch (2701:13): [True: 0, False: 2]
2702
            // file not exist, continue
2703
0
            if (errno == ENOENT) {
  Branch (2703:17): [True: 0, False: 0]
2704
0
                continue;
2705
0
            }
2706
2707
0
            remove_binlog_files_failed = true;
2708
0
            LOG(WARNING) << "failed to remove binlog file:" << file << ", errno:" << errno;
2709
0
            break;
2710
0
        }
2711
2
    }
2712
2
    if (!remove_binlog_files_failed) {
  Branch (2712:9): [True: 2, False: 0]
2713
2
        static_cast<void>(meta->remove(META_COLUMN_FAMILY_INDEX, wait_for_deleted_binlog_keys));
2714
2
    }
2715
2
}
2716
2717
0
Status Tablet::ingest_binlog_metas(RowsetBinlogMetasPB* metas_pb) {
2718
0
    return RowsetMetaManager::ingest_binlog_metas(_data_dir->get_meta(), tablet_uid(), metas_pb);
2719
0
}
2720
2721
480
void Tablet::clear_cache() {
2722
480
    std::vector<RowsetSharedPtr> rowsets;
2723
480
    {
2724
480
        std::shared_lock rlock(get_header_lock());
2725
480
        SCOPED_SIMPLE_TRACE_IF_TIMEOUT(TRACE_TABLET_LOCK_THRESHOLD);
Line
Count
Source
31
480
    SCOPED_SIMPLE_TRACE_TO_STREAM_IF_TIMEOUT(timeout, LOG(WARNING))
Line
Count
Source
41
480
    using namespace std::chrono_literals;                                               \
42
480
    auto VARNAME_LINENUM(scoped_simple_trace) = doris::MonotonicMicros();               \
43
480
    SCOPED_CLEANUP({                                                                    \
Line
Count
Source
34
480
    auto VARNAME_LINENUM(scoped_cleanup) = MakeScopedCleanup([&] { func_body });
44
480
        auto VARNAME_LINENUM(timeout_us) =                                              \
45
480
                std::chrono::duration_cast<std::chrono::microseconds>(timeout).count(); \
46
480
        auto VARNAME_LINENUM(cost_us) =                                                 \
47
480
                doris::MonotonicMicros() - VARNAME_LINENUM(scoped_simple_trace);        \
48
480
        if (VARNAME_LINENUM(cost_us) >= VARNAME_LINENUM(timeout_us)) {                  \
49
480
            stream << "Simple trace cost(us): " << VARNAME_LINENUM(cost_us);            \
50
480
        }                                                                               \
51
480
    })
2726
2727
21.3k
        for (auto& [_, rowset] : rowset_map()) {
  Branch (2727:32): [True: 21.3k, False: 480]
2728
21.3k
            rowsets.push_back(rowset);
2729
21.3k
        }
2730
480
        for (auto& [_, rowset] : stale_rowset_map()) {
  Branch (2730:32): [True: 0, False: 480]
2731
0
            rowsets.push_back(rowset);
2732
0
        }
2733
480
    }
2734
21.3k
    for (auto& rowset : rowsets) {
  Branch (2734:23): [True: 21.3k, False: 480]
2735
21.3k
        rowset->clear_cache();
2736
21.3k
    }
2737
480
}
2738
2739
565
void Tablet::check_table_size_correctness() {
2740
565
    if (!config::enable_table_size_correctness_check) {
  Branch (2740:9): [True: 565, False: 0]
2741
565
        return;
2742
565
    }
2743
0
    const std::vector<RowsetMetaSharedPtr>& all_rs_metas = _tablet_meta->all_rs_metas();
2744
0
    for (const auto& rs_meta : all_rs_metas) {
  Branch (2744:30): [True: 0, False: 0]
2745
0
        int64_t total_segment_size = get_segment_file_size(rs_meta);
2746
0
        int64_t total_inverted_index_size = get_inverted_index_file_size(rs_meta);
2747
0
        if (rs_meta->data_disk_size() != total_segment_size ||
  Branch (2747:13): [True: 0, False: 0]
2748
0
            rs_meta->index_disk_size() != total_inverted_index_size ||
  Branch (2748:13): [True: 0, False: 0]
2749
0
            rs_meta->data_disk_size() + rs_meta->index_disk_size() != rs_meta->total_disk_size()) {
  Branch (2749:13): [True: 0, False: 0]
2750
0
            LOG(WARNING) << "[Local table table size check failed]:"
2751
0
                         << " tablet id: " << rs_meta->tablet_id()
2752
0
                         << ", rowset id:" << rs_meta->rowset_id()
2753
0
                         << ", rowset data disk size:" << rs_meta->data_disk_size()
2754
0
                         << ", rowset real data disk size:" << total_segment_size
2755
0
                         << ", rowset index disk size:" << rs_meta->index_disk_size()
2756
0
                         << ", rowset real index disk size:" << total_inverted_index_size
2757
0
                         << ", rowset total disk size:" << rs_meta->total_disk_size()
2758
0
                         << ", rowset segment path:"
2759
0
                         << StorageResource().remote_segment_path(
2760
0
                                    rs_meta->tablet_id(), rs_meta->rowset_id().to_string(), 0);
2761
0
            DCHECK(false);
2762
0
        }
2763
0
    }
2764
0
}
2765
2766
0
std::string Tablet::get_segment_path(const RowsetMetaSharedPtr& rs_meta, int64_t seg_id) {
2767
0
    std::string segment_path;
2768
0
    if (rs_meta->is_local()) {
  Branch (2768:9): [True: 0, False: 0]
2769
0
        segment_path = local_segment_path(_tablet_path, rs_meta->rowset_id().to_string(), seg_id);
2770
0
    } else {
2771
0
        segment_path = rs_meta->remote_storage_resource().value()->remote_segment_path(
2772
0
                rs_meta->tablet_id(), rs_meta->rowset_id().to_string(), seg_id);
2773
0
    }
2774
0
    return segment_path;
2775
0
}
2776
2777
0
int64_t Tablet::get_segment_file_size(const RowsetMetaSharedPtr& rs_meta) {
2778
0
    const auto& fs = rs_meta->fs();
2779
0
    if (!fs) {
  Branch (2779:9): [True: 0, False: 0]
2780
0
        LOG(WARNING) << "get fs failed, resource_id={}" << rs_meta->resource_id();
2781
0
    }
2782
0
    int64_t total_segment_size = 0;
2783
0
    for (int64_t seg_id = 0; seg_id < rs_meta->num_segments(); seg_id++) {
  Branch (2783:30): [True: 0, False: 0]
2784
0
        std::string segment_path = get_segment_path(rs_meta, seg_id);
2785
0
        int64_t segment_file_size = 0;
2786
0
        auto st = fs->file_size(segment_path, &segment_file_size);
2787
0
        if (!st.ok()) {
  Branch (2787:13): [True: 0, False: 0]
2788
0
            segment_file_size = 0;
2789
0
            LOG(WARNING) << "table size correctness check get segment size failed! msg:"
2790
0
                         << st.to_string() << ", segment path:" << segment_path;
2791
0
        }
2792
0
        total_segment_size += segment_file_size;
2793
0
    }
2794
0
    return total_segment_size;
2795
0
}
2796
2797
0
int64_t Tablet::get_inverted_index_file_size(const RowsetMetaSharedPtr& rs_meta) {
2798
0
    const auto& fs = rs_meta->fs();
2799
0
    if (!fs) {
  Branch (2799:9): [True: 0, False: 0]
2800
0
        LOG(WARNING) << "get fs failed, resource_id={}" << rs_meta->resource_id();
2801
0
    }
2802
0
    int64_t total_inverted_index_size = 0;
2803
2804
0
    if (rs_meta->tablet_schema()->get_inverted_index_storage_format() ==
  Branch (2804:9): [True: 0, False: 0]
2805
0
        InvertedIndexStorageFormatPB::V1) {
2806
0
        const auto& indices = rs_meta->tablet_schema()->inverted_indexes();
2807
0
        for (auto& index : indices) {
  Branch (2807:26): [True: 0, False: 0]
2808
0
            for (int seg_id = 0; seg_id < rs_meta->num_segments(); ++seg_id) {
  Branch (2808:34): [True: 0, False: 0]
2809
0
                std::string segment_path = get_segment_path(rs_meta, seg_id);
2810
0
                int64_t file_size = 0;
2811
2812
0
                std::string inverted_index_file_path =
2813
0
                        InvertedIndexDescriptor::get_index_file_path_v1(
2814
0
                                InvertedIndexDescriptor::get_index_file_path_prefix(segment_path),
2815
0
                                index->index_id(), index->get_index_suffix());
2816
0
                auto st = fs->file_size(inverted_index_file_path, &file_size);
2817
0
                if (!st.ok()) {
  Branch (2817:21): [True: 0, False: 0]
2818
0
                    file_size = 0;
2819
0
                    LOG(WARNING) << " tablet id: " << get_tablet_info().tablet_id
2820
0
                                 << ", rowset id:" << rs_meta->rowset_id()
2821
0
                                 << ", table size correctness check get inverted index v1 "
2822
0
                                    "size failed! msg:"
2823
0
                                 << st.to_string()
2824
0
                                 << ", inverted index path:" << inverted_index_file_path;
2825
0
                }
2826
0
                total_inverted_index_size += file_size;
2827
0
            }
2828
0
        }
2829
0
    } else {
2830
0
        for (int seg_id = 0; seg_id < rs_meta->num_segments(); ++seg_id) {
  Branch (2830:30): [True: 0, False: 0]
2831
0
            int64_t file_size = 0;
2832
0
            std::string segment_path = get_segment_path(rs_meta, seg_id);
2833
0
            std::string inverted_index_file_path = InvertedIndexDescriptor::get_index_file_path_v2(
2834
0
                    InvertedIndexDescriptor::get_index_file_path_prefix(segment_path));
2835
0
            auto st = fs->file_size(inverted_index_file_path, &file_size);
2836
0
            if (!st.ok()) {
  Branch (2836:17): [True: 0, False: 0]
2837
0
                file_size = 0;
2838
0
                if (st.is<NOT_FOUND>()) {
  Branch (2838:21): [True: 0, False: 0]
2839
0
                    LOG(INFO) << " tablet id: " << get_tablet_info().tablet_id
2840
0
                              << ", rowset id:" << rs_meta->rowset_id()
2841
0
                              << ", table size correctness check get inverted index v2 failed "
2842
0
                                 "because file not exist:"
2843
0
                              << inverted_index_file_path;
2844
0
                } else {
2845
0
                    LOG(WARNING) << " tablet id: " << get_tablet_info().tablet_id
2846
0
                                 << ", rowset id:" << rs_meta->rowset_id()
2847
0
                                 << ", table size correctness check get inverted index v2 "
2848
0
                                    "size failed! msg:"
2849
0
                                 << st.to_string()
2850
0
                                 << ", inverted index path:" << inverted_index_file_path;
2851
0
                }
2852
0
            }
2853
0
            total_inverted_index_size += file_size;
2854
0
        }
2855
0
    }
2856
0
    return total_inverted_index_size;
2857
0
}
2858
2859
} // namespace doris