Coverage Report

Created: 2026-10-24 03:36

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