Coverage Report

Created: 2026-08-07 11:46

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