Coverage Report

Created: 2026-06-18 10:04

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/storage/tablet/tablet.h
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
#pragma once
19
20
#include <butil/macros.h>
21
#include <glog/logging.h>
22
23
#include <array>
24
#include <atomic>
25
#include <cstddef>
26
#include <cstdint>
27
#include <functional>
28
#include <memory>
29
#include <mutex>
30
#include <ostream>
31
#include <set>
32
#include <shared_mutex>
33
#include <string>
34
#include <string_view>
35
#include <utility>
36
#include <vector>
37
38
#include "common/atomic_shared_ptr.h"
39
#include "common/config.h"
40
#include "common/metrics/metrics.h"
41
#include "common/status.h"
42
#include "gen_cpp/AgentService_types.h"
43
#include "storage/binlog.h"
44
#include "storage/binlog_config.h"
45
#include "storage/compaction/binlog_compaction_policy.h"
46
#include "storage/data_dir.h"
47
#include "storage/olap_common.h"
48
#include "storage/partial_update_info.h"
49
#include "storage/rowset/rowset.h"
50
#include "storage/rowset/rowset_meta.h"
51
#include "storage/rowset/rowset_reader.h"
52
#include "storage/segment/segment.h"
53
#include "storage/segment/segment_loader.h"
54
#include "storage/tablet/base_tablet.h"
55
#include "storage/version_graph.h"
56
#include "util/once.h"
57
#include "util/slice.h"
58
59
namespace bvar {
60
template <typename T>
61
class Adder;
62
}
63
64
namespace doris {
65
66
class Tablet;
67
class CumulativeCompactionPolicy;
68
class CompactionMixin;
69
class RowsetWriter;
70
struct RowsetWriterContext;
71
class TTabletInfo;
72
class TabletMetaPB;
73
class TupleDescriptor;
74
class CalcDeleteBitmapToken;
75
enum CompressKind : int;
76
class RowsetBinlogMetasPB;
77
78
namespace io {
79
class RemoteFileSystem;
80
} // namespace io
81
class Block;
82
struct RowLocation;
83
enum KeysType : int;
84
enum SortType : int;
85
86
enum TabletStorageType { STORAGE_TYPE_LOCAL, STORAGE_TYPE_REMOTE, STORAGE_TYPE_REMOTE_AND_LOCAL };
87
88
extern bvar::Adder<uint64_t> unused_remote_rowset_num;
89
90
static inline constexpr auto TRACE_TABLET_LOCK_THRESHOLD = std::chrono::seconds(1);
91
92
struct WriteCooldownMetaExecutors {
93
    WriteCooldownMetaExecutors(size_t executor_nums = 5);
94
95
    void stop();
96
97
    void submit(TabletSharedPtr tablet);
98
144k
    size_t _get_executor_pos(int64_t tablet_id) const {
99
144k
        return std::hash<int64_t>()(tablet_id) % _executor_nums;
100
144k
    };
101
    // Each executor is a mpsc to ensure uploads of the same tablet meta are not concurrent
102
    // FIXME(AlexYue): Use mpsc instead of `ThreadPool` with 1 thread
103
    // We use PriorityThreadPool since it would call status inside it's `shutdown` function.
104
    // Consider one situation where the StackTraceCache's singleton is detructed before
105
    // this WriteCooldownMetaExecutors's singleton, then invoking the status would also call
106
    // StackTraceCache which would then result in heap use after free like #23834
107
    std::vector<std::unique_ptr<PriorityThreadPool>> _executors;
108
    std::unordered_set<int64_t> _pending_tablets;
109
    std::mutex _latch;
110
    size_t _executor_nums;
111
};
112
113
class Tablet final : public BaseTablet {
114
public:
115
    Tablet(StorageEngine& engine, TabletMetaSharedPtr tablet_meta, DataDir* data_dir,
116
           const std::string_view& cumulative_compaction_type = "");
117
118
31.7M
    DataDir* data_dir() const { return _data_dir; }
119
1.25M
    int64_t replica_id() const { return _tablet_meta->replica_id(); }
120
121
503k
    std::string tablet_path() const override { return _tablet_path; }
122
139
    std::string row_binlog_path() const {
123
139
        return fmt::format("{}/{}", _tablet_path, FDRowBinlogSuffix);
124
139
    }
125
478k
    std::string get_rowset_path(const RowsetMetaSharedPtr& rowset_meta) const {
126
478k
        if (!rowset_meta->is_local()) {
127
14
            return "";
128
14
        }
129
478k
        return rowset_meta->is_row_binlog() ? row_binlog_path() : tablet_path();
130
478k
    }
131
132
    bool set_tablet_schema_into_rowset_meta();
133
    Status init();
134
    bool init_succeeded();
135
136
    bool is_used();
137
138
    void register_tablet_into_dir();
139
    void deregister_tablet_from_dir();
140
141
    void save_meta();
142
    // Used in clone task, to update local meta when finishing a clone job
143
    Status revise_tablet_meta(const std::vector<RowsetSharedPtr>& to_add,
144
                              const std::vector<RowsetSharedPtr>& to_delete,
145
                              bool is_incremental_clone, bool copy_row_binlog = false);
146
147
    int64_t cumulative_layer_point() const;
148
    void set_cumulative_layer_point(int64_t new_point);
149
    inline int64_t cumulative_promotion_size() const;
150
    inline void set_cumulative_promotion_size(int64_t new_size);
151
152
    // Disk space occupied by tablet, contain local and remote.
153
    size_t tablet_footprint() override;
154
    // Local disk space occupied by tablet.
155
    size_t tablet_local_size();
156
    // Remote disk space occupied by tablet.
157
    size_t tablet_remote_size();
158
159
    size_t num_rows();
160
    size_t version_count() const;
161
    size_t stale_version_count() const;
162
    bool exceed_version_limit(int32_t limit) override;
163
    uint64_t segment_count() const;
164
    Version max_version() const;
165
    CumulativeCompactionPolicy* cumulative_compaction_policy();
166
    BinlogCompactionPolicy* binlog_compaction_policy();
167
168
    // properties encapsulated in TabletSchema
169
    SortType sort_type() const;
170
    size_t sort_col_num() const;
171
    size_t num_columns() const;
172
    size_t num_null_columns() const;
173
    size_t num_short_key_columns() const;
174
    size_t num_rows_per_row_block() const;
175
    double bloom_filter_fpp() const;
176
    size_t next_unique_id() const;
177
    int64_t avg_rs_meta_serialize_size() const;
178
179
    // operation in rowsets
180
    Status add_rowset(RowsetSharedPtr rowset, RowsetSharedPtr row_binlog_rowset = nullptr);
181
    Status create_initial_rowset(const int64_t version);
182
183
    // MUST hold EXCLUSIVE `_meta_lock`.
184
    Status modify_rowsets(std::vector<RowsetSharedPtr>& to_add,
185
                          std::vector<RowsetSharedPtr>& to_delete, bool check_delete = false);
186
    Status modify_row_binlog_rowsets(std::vector<RowsetSharedPtr>& to_add,
187
                                     std::vector<RowsetSharedPtr>& to_delete);
188
    bool rowset_exists_unlocked(const RowsetSharedPtr& rowset);
189
190
    // Add a committed data rowset and its row binlog rowset
191
    Status add_inc_rowset(const RowsetSharedPtr& rowset,
192
                          const RowsetSharedPtr& row_binlog_rowset = nullptr);
193
    /// Delete stale rowset by timing. This delete policy uses now() minutes
194
    /// config::tablet_rowset_expired_stale_sweep_time_sec to compute the deadline of expired rowset
195
    /// to delete.  When rowset is deleted, it will be added to StorageEngine unused map and record
196
    /// need to delete flag.
197
    void delete_expired_stale_rowset();
198
199
    // if quiet is true, no error log will be printed if there are missing versions
200
    Status check_version_integrity(const Version& version, bool quiet = false);
201
    bool check_version_exist(const Version& version) const;
202
    void acquire_version_and_rowsets(
203
            std::vector<std::pair<Version, RowsetSharedPtr>>* version_rowsets) const;
204
205
    // If skip_missing_version is true, skip versions if they are missing.
206
    Status capture_rs_readers(const Version& spec_version, std::vector<RowSetSplits>* rs_splits,
207
                              const CaptureRowsetOps& opts) override;
208
209
    // Find the missed versions until the spec_version.
210
    //
211
    // for example:
212
    //     [0-4][5-5][8-8][9-9][14-14]
213
    // if spec_version = 12, it will return [6, 6], [7, 7], [10, 10], [11, 11], [12, 12]
214
    Versions calc_missed_versions(int64_t spec_version, Versions existing_versions) const override;
215
216
    // meta lock
217
192k
    BthreadSharedMutex& get_header_lock() { return _meta_lock; }
218
44.6k
    std::mutex& get_rowset_update_lock() { return _rowset_update_lock; }
219
42.1k
    std::mutex& get_push_lock() { return _ingest_lock; }
220
6.54M
    std::mutex& get_base_compaction_lock() { return _base_compaction_lock; }
221
8.17M
    std::mutex& get_cumulative_compaction_lock() { return _cumulative_compaction_lock; }
222
528
    std::mutex& get_binlog_compaction_lock() { return _binlog_compaction_lock; }
223
173
    std::shared_mutex& get_meta_store_lock() { return _meta_store_lock; }
224
225
84.0k
    std::shared_timed_mutex& get_migration_lock() { return _migration_lock; }
226
227
194
    std::mutex& get_build_inverted_index_lock() { return _build_inverted_index_lock; }
228
229
    // operation for compaction
230
    bool can_do_compaction(size_t path_hash, CompactionType compaction_type);
231
    bool suitable_for_compaction(
232
            CompactionType compaction_type,
233
            std::shared_ptr<CumulativeCompactionPolicy> cumulative_compaction_policy);
234
235
    uint32_t calc_compaction_score(CompactionType compaction_type,
236
                                   int8_t* prefer_compaction_level = nullptr);
237
238
    // This function to find max continuous version from the beginning.
239
    // For example: If there are 1, 2, 3, 5, 6, 7 versions belongs tablet, then 3 is target.
240
    // 3 will be saved in "version", and 7 will be saved in "max_version", if max_version != nullptr
241
    void max_continuous_version_from_beginning(Version* version, Version* max_version = nullptr);
242
243
0
    void set_bad(bool is_bad) { _is_bad = is_bad; }
244
245
15.3M
    int64_t last_cumu_compaction_failure_time() { return _last_cumu_compaction_failure_millis; }
246
196k
    void set_last_cumu_compaction_failure_time(int64_t millis) {
247
196k
        _last_cumu_compaction_failure_millis = millis;
248
196k
    }
249
250
6.49M
    int64_t last_base_compaction_failure_time() { return _last_base_compaction_failure_millis; }
251
115k
    void set_last_base_compaction_failure_time(int64_t millis) {
252
115k
        _last_base_compaction_failure_millis = millis;
253
115k
    }
254
255
0
    int64_t last_full_compaction_failure_time() { return _last_full_compaction_failure_millis; }
256
0
    void set_last_full_compaction_failure_time(int64_t millis) {
257
0
        _last_full_compaction_failure_millis = millis;
258
0
    }
259
260
186k
    int64_t last_cumu_compaction_success_time() { return _last_cumu_compaction_success_millis; }
261
9.28k
    void set_last_cumu_compaction_success_time(int64_t millis) {
262
9.28k
        _last_cumu_compaction_success_millis = millis;
263
9.28k
    }
264
265
186k
    int64_t last_base_compaction_success_time() { return _last_base_compaction_success_millis; }
266
5.18k
    void set_last_base_compaction_success_time(int64_t millis) {
267
5.18k
        _last_base_compaction_success_millis = millis;
268
5.18k
    }
269
270
0
    int64_t last_full_compaction_success_time() { return _last_full_compaction_success_millis; }
271
0
    void set_last_full_compaction_success_time(int64_t millis) {
272
0
        _last_full_compaction_success_millis = millis;
273
0
    }
274
275
258
    int64_t last_binlog_compaction_success_time(int8_t compaction_level) {
276
258
        DCHECK(compaction_level >= 0 &&
277
258
               compaction_level < BinlogCompactionPolicy::kBinlogCompactionMaxLevel);
278
258
        return _last_binlog_compaction_success_millis[compaction_level].load();
279
258
    }
280
524
    int64_t last_binlog_compaction_failure_time() {
281
524
        return _last_binlog_compaction_failure_millis.load();
282
524
    }
283
    void init_last_binlog_compaction_success_and_failure_time();
284
0
    void set_last_binlog_compaction_success_time(int8_t compaction_level, int64_t millis) {
285
0
        DCHECK(compaction_level >= 0 &&
286
0
               compaction_level < BinlogCompactionPolicy::kBinlogCompactionMaxLevel);
287
0
        _last_binlog_compaction_success_millis[compaction_level] = millis;
288
0
    }
289
258
    void set_last_binlog_compaction_failure_time(int64_t millis) {
290
258
        _last_binlog_compaction_failure_millis = millis;
291
258
    }
292
293
0
    int64_t last_cumu_compaction_schedule_time() { return _last_cumu_compaction_schedule_millis; }
294
196k
    void set_last_cumu_compaction_schedule_time(int64_t millis) {
295
196k
        _last_cumu_compaction_schedule_millis = millis;
296
196k
    }
297
298
0
    int64_t last_base_compaction_schedule_time() { return _last_base_compaction_schedule_millis; }
299
57.5k
    void set_last_base_compaction_schedule_time(int64_t millis) {
300
57.5k
        _last_base_compaction_schedule_millis = millis;
301
57.5k
    }
302
303
0
    int64_t last_full_compaction_schedule_time() { return _last_full_compaction_schedule_millis; }
304
0
    void set_last_full_compaction_schedule_time(int64_t millis) {
305
0
        _last_full_compaction_schedule_millis = millis;
306
0
    }
307
308
    void delete_all_files();
309
310
    void check_tablet_path_exists();
311
312
    std::vector<RowsetSharedPtr> pick_candidate_rowsets_to_cumulative_compaction();
313
    // MUST hold shared `_meta_lock`. Use this when the caller already holds the
314
    // header lock (e.g. the time-series cumulative score path under
315
    // suitable_for_compaction) to avoid recursive shared acquisition.
316
    std::vector<RowsetSharedPtr> pick_candidate_rowsets_to_cumulative_compaction_unlocked();
317
    std::vector<RowsetSharedPtr> pick_candidate_rowsets_to_base_compaction();
318
    std::vector<RowsetSharedPtr> pick_candidate_rowsets_to_full_compaction();
319
    std::vector<RowsetSharedPtr> pick_candidate_rowsets_to_binlog_compaction();
320
    std::vector<RowsetSharedPtr> pick_candidate_rowsets_to_build_inverted_index(
321
            const std::set<int64_t>& alter_index_uids, bool is_drop_op);
322
323
    // used for single compaction to get the local versions
324
    // Single compaction does not require remote rowsets and cannot violate the cooldown semantics
325
    std::vector<Version> get_all_local_versions();
326
327
    void calculate_cumulative_point();
328
    // TODO(ygl):
329
0
    bool is_primary_replica() { return false; }
330
331
    // return true if the checkpoint is actually done
332
    bool do_tablet_meta_checkpoint();
333
334
    // Check whether the rowset is useful or not, unuseful rowset can be swept up then.
335
    // Rowset which is under tablet's management is useful, i.e. rowset is in
336
    // _rs_version_map, or _stale_rs_version_map.
337
    // Rowset whose version range is not covered by this tablet is also useful.
338
    bool rowset_meta_is_useful(RowsetMetaSharedPtr rowset_meta);
339
340
    void build_tablet_report_info(TTabletInfo* tablet_info,
341
                                  bool enable_consecutive_missing_check = false,
342
                                  bool enable_path_check = false);
343
344
    // return a json string to show the compaction status of this tablet
345
    void get_compaction_status(std::string* json_result);
346
347
    static Status prepare_compaction_and_calculate_permits(
348
            CompactionType compaction_type, const TabletSharedPtr& tablet,
349
            std::shared_ptr<CompactionMixin>& compaction, int64_t& permits,
350
            int8_t prefer_compaction_level = -1);
351
352
    void execute_compaction(CompactionMixin& compaction);
353
354
    void set_cumulative_compaction_policy(
355
0
            std::shared_ptr<CumulativeCompactionPolicy> cumulative_compaction_policy) {
356
0
        _cumulative_compaction_policy = cumulative_compaction_policy;
357
0
    }
358
359
0
    std::shared_ptr<CumulativeCompactionPolicy> get_cumulative_compaction_policy() {
360
0
        return _cumulative_compaction_policy;
361
0
    }
362
363
196k
    void set_last_cumu_compaction_status(std::string status) {
364
196k
        _last_cumu_compaction_status = std::move(status);
365
196k
    }
366
367
0
    std::string get_last_cumu_compaction_status() { return _last_cumu_compaction_status; }
368
369
115k
    void set_last_base_compaction_status(std::string status) {
370
115k
        _last_base_compaction_status = std::move(status);
371
115k
    }
372
373
0
    std::string get_last_base_compaction_status() { return _last_base_compaction_status; }
374
375
0
    void set_last_full_compaction_status(std::string status) {
376
0
        _last_full_compaction_status = std::move(status);
377
0
    }
378
379
0
    std::string get_last_full_compaction_status() { return _last_full_compaction_status; }
380
381
258
    void set_last_binlog_compaction_status(std::string status) {
382
258
        _last_binlog_compaction_status = std::move(status);
383
258
    }
384
385
0
    std::string get_last_binlog_compaction_status() { return _last_binlog_compaction_status; }
386
387
    std::tuple<int64_t, int64_t> get_visible_version_and_time() const;
388
389
289k
    void set_visible_version(const std::shared_ptr<const VersionWithTime>& visible_version) {
390
289k
        _visible_version.store(visible_version);
391
289k
    }
392
393
0
    inline bool all_beta() const {
394
0
        std::shared_lock rdlock(_meta_lock);
395
0
        return _tablet_meta->all_beta();
396
0
    }
397
398
0
    const TabletSchemaSPtr& tablet_schema_unlocked() const { return _max_version_schema; }
399
400
    Result<std::unique_ptr<RowsetWriter>> create_rowset_writer(RowsetWriterContext& context,
401
                                                               bool vertical) override;
402
403
    Result<std::unique_ptr<RowsetWriter>> create_transient_rowset_writer(
404
            const Rowset& rowset, std::shared_ptr<PartialUpdateInfo> partial_update_info,
405
            int64_t txn_expiration = 0) override;
406
    Result<std::unique_ptr<RowsetWriter>> create_transient_rowset_writer(
407
            RowsetWriterContext& context, const RowsetId& rowset_id);
408
409
    Status create_rowset(const RowsetMetaSharedPtr& rowset_meta, RowsetSharedPtr* rowset);
410
411
    // MUST hold EXCLUSIVE `_meta_lock`
412
    void add_rowsets(const std::vector<RowsetSharedPtr>& to_add, bool copy_row_binlog = false);
413
    // MUST hold EXCLUSIVE `_meta_lock`
414
    Status delete_rowsets(const std::vector<RowsetSharedPtr>& to_delete, bool move_to_stale,
415
                          bool copy_row_binlog = false);
416
417
    // MUST hold SHARED `_meta_lock`
418
10.0k
    const auto& rowset_map() const { return _rs_version_map; }
419
    // MUST hold SHARED `_meta_lock`
420
10.0k
    const auto& stale_rowset_map() const { return _stale_rs_version_map; }
421
    // MUST hold SHARED `_meta_lock`
422
0
    const auto& row_binlog_rowset_map() const { return _row_binlog_rs_version_map; }
423
424
    ////////////////////////////////////////////////////////////////////////////
425
    // begin cooldown functions
426
    ////////////////////////////////////////////////////////////////////////////
427
980k
    int64_t storage_policy_id() const { return _tablet_meta->storage_policy_id(); }
428
    void set_storage_policy_id(int64_t id) { _tablet_meta->set_storage_policy_id(id); }
429
430
3.88M
    int64_t last_failed_follow_cooldown_time() const { return _last_failed_follow_cooldown_time; }
431
432
    // Cooldown to remote fs.
433
    Status cooldown(RowsetSharedPtr rowset = nullptr);
434
435
    RowsetSharedPtr pick_cooldown_rowset();
436
437
    RowsetSharedPtr need_cooldown(int64_t* cooldown_timestamp, size_t* file_size);
438
439
    struct CooldownConf {
440
        int64_t term = -1;
441
        int64_t cooldown_replica_id = -1;
442
    };
443
444
7
    CooldownConf cooldown_conf() const {
445
7
        std::shared_lock rlock(_cooldown_conf_lock);
446
7
        return _cooldown_conf;
447
7
    }
448
449
21
    CooldownConf cooldown_conf_unlocked() const { return _cooldown_conf; }
450
451
    // Return `true` if update success
452
    bool update_cooldown_conf(int64_t cooldown_term, int64_t cooldown_replica_id);
453
454
    Status remove_all_remote_rowsets();
455
456
    void record_unused_remote_rowset(const RowsetId& rowset_id, const std::string& resource,
457
                                     int64_t num_segments);
458
459
    uint32_t calc_cold_data_compaction_score() const;
460
461
194
    std::mutex& get_cold_compaction_lock() { return _cold_compaction_lock; }
462
463
0
    std::shared_mutex& get_cooldown_conf_lock() { return _cooldown_conf_lock; }
464
465
    static void async_write_cooldown_meta(TabletSharedPtr tablet);
466
    // Return `ABORTED` if should not to retry again
467
    Status write_cooldown_meta();
468
    ////////////////////////////////////////////////////////////////////////////
469
    // end cooldown functions
470
    ////////////////////////////////////////////////////////////////////////////
471
472
    CalcDeleteBitmapExecutor* calc_delete_bitmap_executor() override;
473
    Status save_delete_bitmap(const TabletTxnInfo* txn_info, int64_t txn_id,
474
                              DeleteBitmapPtr delete_bitmap, RowsetWriter* rowset_writer,
475
                              const RowsetIdUnorderedSet& cur_rowset_ids, int64_t lock_id = -1,
476
                              int64_t next_visible_version = -1) override;
477
478
    void merge_delete_bitmap(const DeleteBitmap& delete_bitmap);
479
    bool check_all_rowset_segment();
480
481
    void update_max_version_schema(const TabletSchemaSPtr& tablet_schema);
482
483
    void set_skip_compaction(bool skip,
484
                             CompactionType compaction_type = CompactionType::CUMULATIVE_COMPACTION,
485
                             int64_t start = -1);
486
    bool should_skip_compaction(CompactionType compaction_type, int64_t now);
487
488
    std::vector<std::string> get_binlog_filepath(std::string_view binlog_version) const;
489
    std::pair<std::string, int64_t> get_binlog_info(std::string_view binlog_version) const;
490
    std::string get_rowset_binlog_meta(std::string_view binlog_version,
491
                                       std::string_view rowset_id) const;
492
    Status get_rowset_binlog_metas(const std::vector<int64_t>& binlog_versions,
493
                                   RowsetBinlogMetasPB* metas_pb);
494
    Status get_rowset_binlog_metas(Version binlog_versions, RowsetBinlogMetasPB* metas_pb);
495
    std::string get_segment_filepath(std::string_view rowset_id,
496
                                     std::string_view segment_index) const;
497
    std::string get_segment_filepath(std::string_view rowset_id, int64_t segment_index) const;
498
    bool can_add_binlog(uint64_t total_binlog_size) const;
499
    void gc_binlogs(int64_t version);
500
    Status ingest_binlog_metas(RowsetBinlogMetasPB* metas_pb);
501
502
    void report_error(const Status& st);
503
504
0
    inline int64_t get_io_error_times() const { return _io_error_times; }
505
506
1.24M
    inline bool is_io_error_too_times() const {
507
1.24M
        return config::max_tablet_io_errors > 0 && _io_error_times >= config::max_tablet_io_errors;
508
1.24M
    }
509
510
45.8k
    int64_t get_table_id() { return _tablet_meta->table_id(); }
511
512
    // binlog related functions
513
83.2k
    bool enable_binlog() const {
514
83.2k
        return config::enable_feature_binlog && _tablet_meta->binlog_config().is_enable();
515
83.2k
    }
516
83.2k
    bool enable_ccr_binlog() const {
517
83.2k
        return enable_binlog() && _tablet_meta->binlog_config().is_ccr_binlog_format();
518
83.2k
    }
519
389M
    bool enable_row_binlog() const {
520
389M
        return _tablet_meta->binlog_config().is_enable() &&
521
389M
               _tablet_meta->binlog_config().is_row_binlog_format();
522
389M
    }
523
524
0
    int64_t binlog_ttl_ms() const { return _tablet_meta->binlog_config().ttl_seconds(); }
525
0
    int64_t binlog_max_bytes() const { return _tablet_meta->binlog_config().max_bytes(); }
526
527
    void set_binlog_config(BinlogConfig binlog_config);
528
529
    // row_binlog
530
9
    int32_t row_binlog_schema_hash() const { return _tablet_meta->row_binlog_schema_hash(); }
531
532
0
    void set_is_full_compaction_running(bool is_full_compaction_running) {
533
0
        _is_full_compaction_running = is_full_compaction_running;
534
0
    }
535
0
    inline bool is_full_compaction_running() const { return _is_full_compaction_running; }
536
    void clear_cache() override;
537
538
    int32_t get_compaction_score() const { return _compaction_score; }
539
540
0
    void set_compaction_score(int32_t compaction_score) { _compaction_score = compaction_score; }
541
542
59.5k
    void add_compaction_score(int32_t score) {
543
59.5k
        if (_compaction_score < 0) {
544
19.5k
            return;
545
19.5k
        }
546
40.0k
        _compaction_score += score;
547
40.0k
    }
548
549
0
    void minus_compaction_score(int32_t score) {
550
0
        if (_compaction_score < 0) {
551
0
            return;
552
0
        }
553
0
        _compaction_score -= score;
554
0
    }
555
556
    Status prepare_txn(TPartitionId partition_id, TTransactionId transaction_id,
557
                       const PUniqueId& load_id, bool ingest);
558
    // TODO: commit_txn
559
560
private:
561
    Status _init_once_action();
562
    bool _contains_rowset(const RowsetId rowset_id);
563
    Status _contains_version(const Version& version);
564
    Status _add_row_binlog_rowset_unlocked(const RowsetSharedPtr& rowset,
565
                                           const RowsetSharedPtr& row_binlog_rowset);
566
567
    // Returns:
568
    // version: the max continuous version from beginning
569
    // max_version: the max version of this tablet
570
    void _max_continuous_version_from_beginning_unlocked(Version* version, Version* max_version,
571
                                                         bool* has_version_cross) const;
572
    RowsetSharedPtr _rowset_with_largest_size();
573
    /// Delete stale rowset by version. This method not only delete the version in expired rowset map,
574
    /// but also delete the version in rowset meta vector.
575
    void _delete_stale_rowset_by_version(const Version& version);
576
577
    uint32_t _calc_cumulative_compaction_score(
578
            std::shared_ptr<CumulativeCompactionPolicy> cumulative_compaction_policy);
579
    uint32_t _calc_base_compaction_score() const;
580
    uint32_t _calc_binlog_compaction_score(int8_t* prefer_compaction_level = nullptr);
581
582
    std::vector<RowsetSharedPtr> _pick_visible_rowsets_to_compaction(int64_t min_start_version,
583
                                                                     int64_t max_start_version);
584
    // MUST hold shared `_meta_lock`.
585
    std::vector<RowsetSharedPtr> _pick_visible_rowsets_to_compaction_unlocked(
586
            int64_t min_start_version, int64_t max_start_version);
587
588
    void _init_context_common_fields(RowsetWriterContext& context);
589
590
    ////////////////////////////////////////////////////////////////////////////
591
    // begin cooldown functions
592
    ////////////////////////////////////////////////////////////////////////////
593
    Status _cooldown_data(RowsetSharedPtr rowset);
594
    Status _follow_cooldowned_data();
595
    Status _read_cooldown_meta(const StorageResource& storage_resource,
596
                               TabletMetaPB* tablet_meta_pb);
597
    bool _has_data_to_cooldown();
598
    int64_t _get_newest_cooldown_time(const RowsetSharedPtr& rowset);
599
    ////////////////////////////////////////////////////////////////////////////
600
    // end cooldown functions
601
    ////////////////////////////////////////////////////////////////////////////
602
603
    void _clear_cache_by_rowset(const BetaRowsetSharedPtr& rowset);
604
    void check_table_size_correctness();
605
    std::string get_segment_path(const RowsetMetaSharedPtr& rs_meta, int64_t seg_id);
606
    int64_t get_segment_file_size(const RowsetMetaSharedPtr& rs_meta);
607
    int64_t get_inverted_index_file_size(const RowsetMetaSharedPtr& rs_meta);
608
609
public:
610
    static const int64_t K_INVALID_CUMULATIVE_POINT = -1;
611
612
private:
613
    StorageEngine& _engine;
614
    DataDir* _data_dir = nullptr;
615
616
    std::string _tablet_path;
617
618
    DorisCallOnce<Status> _init_once;
619
    // meta store lock is used for prevent 2 threads do checkpoint concurrently
620
    // it will be used in econ-mode in the future
621
    std::shared_mutex _meta_store_lock;
622
    std::mutex _ingest_lock;
623
    std::mutex _base_compaction_lock;
624
    std::mutex _cumulative_compaction_lock;
625
    std::mutex _binlog_compaction_lock;
626
    std::shared_timed_mutex _migration_lock;
627
    std::mutex _build_inverted_index_lock;
628
629
    // In unique key table with MoW, we should guarantee that only one
630
    // writer can update rowset and delete bitmap at the same time.
631
    // We use a separate lock rather than _meta_lock, to avoid blocking read queries
632
    // during publish_txn, which might take hundreds of milliseconds
633
    mutable std::mutex _rowset_update_lock;
634
635
    // if this tablet is broken, set to true. default is false
636
    std::atomic<bool> _is_bad;
637
    // timestamp of last cumu compaction failure
638
    std::atomic<int64_t> _last_cumu_compaction_failure_millis;
639
    // timestamp of last base compaction failure
640
    std::atomic<int64_t> _last_base_compaction_failure_millis;
641
    // timestamp of last full compaction failure
642
    std::atomic<int64_t> _last_full_compaction_failure_millis;
643
    // timestamp of last cumu compaction success
644
    std::atomic<int64_t> _last_cumu_compaction_success_millis;
645
    // timestamp of last base compaction success
646
    std::atomic<int64_t> _last_base_compaction_success_millis;
647
    // timestamp of last full compaction success
648
    std::atomic<int64_t> _last_full_compaction_success_millis;
649
    // timestamp of last binlog compaction success for each compaction level
650
    std::array<std::atomic<int64_t>, BinlogCompactionPolicy::kBinlogCompactionMaxLevel>
651
            _last_binlog_compaction_success_millis;
652
    // timestamp of last binlog compaction failure
653
    std::atomic<int64_t> _last_binlog_compaction_failure_millis;
654
    // timestamp of last cumu compaction schedule time
655
    std::atomic<int64_t> _last_cumu_compaction_schedule_millis;
656
    // timestamp of last base compaction schedule time
657
    std::atomic<int64_t> _last_base_compaction_schedule_millis;
658
    // timestamp of last full compaction schedule time
659
    std::atomic<int64_t> _last_full_compaction_schedule_millis;
660
    std::atomic<int64_t> _cumulative_point;
661
    std::atomic<int64_t> _cumulative_promotion_size;
662
    std::atomic<int32_t> _newly_created_rowset_num;
663
    std::atomic<int64_t> _last_checkpoint_time;
664
    std::string _last_cumu_compaction_status;
665
    std::string _last_base_compaction_status;
666
    std::string _last_full_compaction_status;
667
    std::string _last_binlog_compaction_status;
668
669
    // cumulative compaction policy
670
    std::shared_ptr<CumulativeCompactionPolicy> _cumulative_compaction_policy;
671
    std::string_view _cumulative_compaction_type;
672
    std::shared_ptr<BinlogCompactionPolicy> _binlog_compaction_policy;
673
674
    // use a separate thread to check all tablets paths existence
675
    std::atomic<bool> _is_tablet_path_exists;
676
677
    int64_t _last_missed_version;
678
    int64_t _last_missed_time_s;
679
680
    bool _skip_cumu_compaction = false;
681
    int64_t _skip_cumu_compaction_ts;
682
683
    bool _skip_base_compaction = false;
684
    int64_t _skip_base_compaction_ts;
685
686
    bool _skip_binlog_compaction = false;
687
    int64_t _skip_binlog_compaction_ts;
688
689
    // cooldown related
690
    CooldownConf _cooldown_conf;
691
    // `_cooldown_conf_lock` is used to serialize update cooldown conf and all operations that:
692
    // 1. read cooldown conf
693
    // 2. upload rowsets to remote storage
694
    // 3. update cooldown meta id
695
    mutable std::shared_mutex _cooldown_conf_lock;
696
    // `_cold_compaction_lock` is used to serialize cold data compaction and all operations that
697
    // may delete compaction input rowsets.
698
    std::mutex _cold_compaction_lock;
699
    int64_t _last_failed_follow_cooldown_time = 0;
700
701
    int64_t _io_error_times = 0;
702
703
    // partition's visible version. it sync from fe, but not real-time.
704
    atomic_shared_ptr<const VersionWithTime> _visible_version;
705
706
    std::atomic_bool _is_full_compaction_running = false;
707
708
    int32_t _compaction_score = -1;
709
    int32_t _score_check_cnt = 0;
710
};
711
712
201k
inline CumulativeCompactionPolicy* Tablet::cumulative_compaction_policy() {
713
201k
    return _cumulative_compaction_policy.get();
714
201k
}
715
716
258
inline BinlogCompactionPolicy* Tablet::binlog_compaction_policy() {
717
258
    return _binlog_compaction_policy.get();
718
258
}
719
720
15.9M
inline bool Tablet::init_succeeded() {
721
15.9M
    return _init_once.has_called() && _init_once.stored_result().ok();
722
15.9M
}
723
724
17.3M
inline bool Tablet::is_used() {
725
17.3M
    return !_is_bad && _data_dir->is_used();
726
17.3M
}
727
728
284k
inline void Tablet::register_tablet_into_dir() {
729
284k
    _data_dir->register_tablet(this);
730
284k
}
731
732
5.11k
inline void Tablet::deregister_tablet_from_dir() {
733
5.11k
    _data_dir->deregister_tablet(this);
734
5.11k
}
735
736
1.05M
inline int64_t Tablet::cumulative_layer_point() const {
737
1.05M
    return _cumulative_point;
738
1.05M
}
739
740
9.58k
inline void Tablet::set_cumulative_layer_point(int64_t new_point) {
741
    // cumulative point should only be reset to -1, or be increased
742
18.4E
    CHECK(new_point == Tablet::K_INVALID_CUMULATIVE_POINT || new_point >= _cumulative_point)
743
18.4E
            << "Unexpected cumulative point: " << new_point
744
18.4E
            << ", origin: " << _cumulative_point.load();
745
9.58k
    _cumulative_point = new_point;
746
9.58k
}
747
748
194k
inline int64_t Tablet::cumulative_promotion_size() const {
749
194k
    return _cumulative_promotion_size;
750
194k
}
751
752
331k
inline void Tablet::set_cumulative_promotion_size(int64_t new_size) {
753
331k
    _cumulative_promotion_size = new_size;
754
331k
}
755
756
// TODO(lingbin): Why other methods that need to get information from _tablet_meta
757
// are not locked, here needs a comment to explain.
758
29.8k
inline size_t Tablet::tablet_footprint() {
759
29.8k
    std::shared_lock rdlock(_meta_lock);
760
29.8k
    return _tablet_meta->tablet_footprint();
761
29.8k
}
762
763
3.23M
inline size_t Tablet::tablet_local_size() {
764
3.23M
    std::shared_lock rdlock(_meta_lock);
765
3.23M
    return _tablet_meta->tablet_local_size();
766
3.23M
}
767
768
3.23M
inline size_t Tablet::tablet_remote_size() {
769
3.23M
    std::shared_lock rdlock(_meta_lock);
770
3.23M
    return _tablet_meta->tablet_remote_size();
771
3.23M
}
772
773
// TODO(lingbin): Why other methods which need to get information from _tablet_meta
774
// are not locked, here needs a comment to explain.
775
inline size_t Tablet::num_rows() {
776
    std::shared_lock rdlock(_meta_lock);
777
    return _tablet_meta->num_rows();
778
}
779
780
4.80M
inline size_t Tablet::version_count() const {
781
4.80M
    std::shared_lock rdlock(_meta_lock);
782
4.80M
    return _tablet_meta->version_count();
783
4.80M
}
784
785
42.0k
inline size_t Tablet::stale_version_count() const {
786
42.0k
    std::shared_lock rdlock(_meta_lock);
787
42.0k
    return _tablet_meta->stale_version_count();
788
42.0k
}
789
790
473k
inline Version Tablet::max_version() const {
791
473k
    std::shared_lock rdlock(_meta_lock);
792
473k
    return _tablet_meta->max_version();
793
473k
}
794
795
4.72M
inline uint64_t Tablet::segment_count() const {
796
4.72M
    std::shared_lock rdlock(_meta_lock);
797
4.72M
    uint64_t segment_nums = 0;
798
8.47M
    for (const auto& [_, rs_meta] : _tablet_meta->all_rs_metas()) {
799
8.47M
        segment_nums += rs_meta->num_segments();
800
8.47M
    }
801
4.72M
    return segment_nums;
802
4.72M
}
803
804
0
inline SortType Tablet::sort_type() const {
805
0
    return _tablet_meta->tablet_schema()->sort_type();
806
0
}
807
808
0
inline size_t Tablet::sort_col_num() const {
809
0
    return _tablet_meta->tablet_schema()->sort_col_num();
810
0
}
811
812
0
inline size_t Tablet::num_columns() const {
813
0
    return _tablet_meta->tablet_schema()->num_columns();
814
0
}
815
816
0
inline size_t Tablet::num_null_columns() const {
817
0
    return _tablet_meta->tablet_schema()->num_null_columns();
818
0
}
819
820
0
inline size_t Tablet::num_short_key_columns() const {
821
0
    return _tablet_meta->tablet_schema()->num_short_key_columns();
822
0
}
823
824
0
inline size_t Tablet::num_rows_per_row_block() const {
825
0
    return _tablet_meta->tablet_schema()->num_rows_per_row_block();
826
0
}
827
828
0
inline double Tablet::bloom_filter_fpp() const {
829
0
    return _tablet_meta->tablet_schema()->bloom_filter_fpp();
830
0
}
831
832
0
inline size_t Tablet::next_unique_id() const {
833
0
    return _tablet_meta->tablet_schema()->next_column_unique_id();
834
0
}
835
836
42.0k
inline int64_t Tablet::avg_rs_meta_serialize_size() const {
837
42.0k
    return _tablet_meta->avg_rs_meta_serialize_size();
838
42.0k
}
839
840
class TabletCopyType {
841
public:
842
    static constexpr int32_t DEFAULT = TTabletCopyType::DATA | TTabletCopyType::CCR_BINLOG;
843
844
644
    static bool has(int32_t copy_type, TTabletCopyType::type flag) {
845
644
        return (copy_type & static_cast<int32_t>(flag)) != 0;
846
644
    }
847
848
322
    static Status validate(int32_t copy_type) {
849
322
        if (copy_type <= 0 || (copy_type & ~all_types()) != 0) {
850
0
            return Status::Error<ErrorCode::INVALID_ARGUMENT>(
851
0
                    "invalid copy_type bitmask: {}, valid bits: {}", copy_type, all_types());
852
0
        }
853
322
        return Status::OK();
854
322
    }
855
856
private:
857
322
    static constexpr int32_t all_types() {
858
322
        return TTabletCopyType::DATA | TTabletCopyType::ROW_BINLOG | TTabletCopyType::CCR_BINLOG;
859
322
    }
860
};
861
862
} // namespace doris