Coverage Report

Created: 2026-05-16 15:51

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