Coverage Report

Created: 2025-08-27 05:46

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