Coverage Report

Created: 2025-05-21 20:37

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