Coverage Report

Created: 2026-05-28 10:49

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