Coverage Report

Created: 2025-04-22 12:18

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