Coverage Report

Created: 2026-03-14 13:33

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