Coverage Report

Created: 2025-09-16 07:56

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