Coverage Report

Created: 2026-01-12 19:16

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