Coverage Report

Created: 2025-10-28 06:27

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