Coverage Report

Created: 2026-06-02 11:59

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