Coverage Report

Created: 2026-10-10 01:33

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