Coverage Report

Created: 2025-05-21 10:06

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