Coverage Report

Created: 2025-04-30 15:20

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