Coverage Report

Created: 2025-10-14 05:20

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/doris/be/src/cloud/cloud_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 <memory>
21
22
#include "olap/base_tablet.h"
23
#include "olap/partial_update_info.h"
24
#include "olap/rowset/rowset.h"
25
26
namespace doris {
27
28
class CloudStorageEngine;
29
30
enum class WarmUpTriggerSource : int { NONE, SYNC_ROWSET, EVENT_DRIVEN, JOB };
31
32
enum class WarmUpProgress : int { NONE, DOING, DONE };
33
34
struct WarmUpState {
35
    WarmUpTriggerSource trigger_source {WarmUpTriggerSource::NONE};
36
    WarmUpProgress progress {WarmUpProgress::NONE};
37
38
55
    bool operator==(const WarmUpState& other) const {
39
55
        return trigger_source == other.trigger_source && progress == other.progress;
40
55
    }
41
};
42
43
struct SyncRowsetStats {
44
    int64_t get_remote_rowsets_num {0};
45
    int64_t get_remote_rowsets_rpc_ns {0};
46
47
    int64_t get_local_delete_bitmap_rowsets_num {0};
48
    int64_t get_remote_delete_bitmap_rowsets_num {0};
49
    int64_t get_remote_delete_bitmap_key_count {0};
50
    int64_t get_remote_delete_bitmap_bytes {0};
51
    int64_t get_remote_delete_bitmap_rpc_ns {0};
52
53
    int64_t get_remote_tablet_meta_rpc_ns {0};
54
    int64_t tablet_meta_cache_hit {0};
55
    int64_t tablet_meta_cache_miss {0};
56
};
57
58
struct SyncOptions {
59
    bool warmup_delta_data = false;
60
    bool sync_delete_bitmap = true;
61
    bool full_sync = false;
62
    bool merge_schema = false;
63
    int64_t query_version = -1;
64
};
65
66
struct RecycledRowsets {
67
    RowsetId rowset_id;
68
    int64_t num_segments;
69
    std::vector<std::string> index_file_names;
70
};
71
72
class CloudTablet final : public BaseTablet {
73
public:
74
    CloudTablet(CloudStorageEngine& engine, TabletMetaSharedPtr tablet_meta);
75
76
    ~CloudTablet() override;
77
78
    bool exceed_version_limit(int32_t limit) override;
79
80
    Result<std::unique_ptr<RowsetWriter>> create_rowset_writer(RowsetWriterContext& context,
81
                                                               bool vertical) override;
82
83
    Status capture_rs_readers(const Version& spec_version, std::vector<RowSetSplits>* rs_splits,
84
                              const CaptureRsReaderOptions& opts) override;
85
    Status capture_rs_readers_internal(const Version& spec_version,
86
                                       std::vector<RowSetSplits>* rs_splits);
87
88
    // Capture rowset readers with cache preference optimization.
89
    // This method prioritizes using cached/warmed-up rowsets when building version paths,
90
    // avoiding cold data reads when possible. It uses capture_consistent_versions_prefer_cache
91
    // to find a consistent version path that prefers already warmed-up rowsets.
92
    Status capture_rs_readers_prefer_cache(const Version& spec_version,
93
                                           std::vector<RowSetSplits>* rs_splits);
94
95
    // Capture rowset readers with query freshness tolerance.
96
    // This method finds a consistent version path where all rowsets are warmed up,
97
    // but allows fallback to normal capture if there are newer rowsets that should be
98
    // visible (based on freshness tolerance) but haven't been warmed up yet.
99
    // For merge-on-write tables, uses special validation to ensure data correctness.
100
    //
101
    // IMPORTANT: The returned version may be smaller than the requested version if newer
102
    // data hasn't been warmed up yet. This can cause different tablets in the same query
103
    // to read from different versions, potentially leading to inconsistent query results.
104
    //
105
    // @param query_freshness_tolerance_ms: Time tolerance in milliseconds. Rowsets that
106
    //        became visible within this time range (after current_time - query_freshness_tolerance_ms)
107
    //        can be skipped if not warmed up. However, if older rowsets (before this time point)
108
    //        are not warmed up, the method will fallback to normal capture.
109
    Status capture_rs_readers_with_freshness_tolerance(const Version& spec_version,
110
                                                       std::vector<RowSetSplits>* rs_splits,
111
                                                       int64_t query_freshness_tolerance_ms);
112
113
    Status capture_consistent_rowsets_unlocked(
114
            const Version& spec_version, std::vector<RowsetSharedPtr>* rowsets) const override;
115
116
0
    size_t tablet_footprint() override {
117
0
        return _approximate_data_size.load(std::memory_order_relaxed);
118
0
    }
119
120
    std::string tablet_path() const override;
121
122
    // clang-format off
123
2
    int64_t fetch_add_approximate_num_rowsets (int64_t x) { return _approximate_num_rowsets .fetch_add(x, std::memory_order_relaxed); }
124
0
    int64_t fetch_add_approximate_num_segments(int64_t x) { return _approximate_num_segments.fetch_add(x, std::memory_order_relaxed); }
125
0
    int64_t fetch_add_approximate_num_rows    (int64_t x) { return _approximate_num_rows    .fetch_add(x, std::memory_order_relaxed); }
126
0
    int64_t fetch_add_approximate_data_size   (int64_t x) { return _approximate_data_size   .fetch_add(x, std::memory_order_relaxed); }
127
2
    int64_t fetch_add_approximate_cumu_num_rowsets (int64_t x) { return _approximate_cumu_num_rowsets.fetch_add(x, std::memory_order_relaxed); }
128
0
    int64_t fetch_add_approximate_cumu_num_deltas   (int64_t x) { return _approximate_cumu_num_deltas.fetch_add(x, std::memory_order_relaxed); }
129
    // clang-format on
130
131
    // meta lock must be held when calling this function
132
    void reset_approximate_stats(int64_t num_rowsets, int64_t num_segments, int64_t num_rows,
133
                                 int64_t data_size);
134
135
    // return a json string to show the compaction status of this tablet
136
    void get_compaction_status(std::string* json_result);
137
138
    // Synchronize the rowsets from meta service.
139
    // If tablet state is not `TABLET_RUNNING`, sync tablet meta and all visible rowsets.
140
    // If `query_version` > 0 and local max_version of the tablet >= `query_version`, do nothing.
141
    // If 'need_download_data_async' is true, it means that we need to download the new version
142
    // rowsets datum async.
143
    Status sync_rowsets(const SyncOptions& options = {}, SyncRowsetStats* stats = nullptr);
144
145
    // Synchronize the tablet meta from meta service.
146
    Status sync_meta();
147
148
    // If `version_overlap` is true, function will delete rowsets with overlapped version in this tablet.
149
    // If 'warmup_delta_data' is true, download the new version rowset data in background.
150
    // MUST hold EXCLUSIVE `_meta_lock`.
151
    // If 'need_download_data_async' is true, it means that we need to download the new version
152
    // rowsets datum async.
153
    void add_rowsets(std::vector<RowsetSharedPtr> to_add, bool version_overlap,
154
                     std::unique_lock<std::shared_mutex>& meta_lock,
155
                     bool warmup_delta_data = false);
156
157
    // MUST hold EXCLUSIVE `_meta_lock`.
158
    void delete_rowsets(const std::vector<RowsetSharedPtr>& to_delete,
159
                        std::unique_lock<std::shared_mutex>& meta_lock);
160
161
    // When the tablet is dropped, we need to recycle cached data:
162
    // 1. The data in file cache
163
    // 2. The memory in tablet cache
164
    void clear_cache() override;
165
166
    // Return number of deleted stale rowsets
167
    uint64_t delete_expired_stale_rowsets();
168
169
0
    bool has_stale_rowsets() const { return !_stale_rs_version_map.empty(); }
170
171
    int64_t get_cloud_base_compaction_score() const;
172
    int64_t get_cloud_cumu_compaction_score() const;
173
174
2
    int64_t max_version_unlocked() const override { return _max_version; }
175
3
    int64_t base_compaction_cnt() const { return _base_compaction_cnt; }
176
3
    int64_t cumulative_compaction_cnt() const { return _cumulative_compaction_cnt; }
177
0
    int64_t full_compaction_cnt() const { return _full_compaction_cnt; }
178
6
    int64_t cumulative_layer_point() const {
179
6
        return _cumulative_point.load(std::memory_order_relaxed);
180
6
    }
181
182
0
    void set_base_compaction_cnt(int64_t cnt) { _base_compaction_cnt = cnt; }
183
0
    void set_cumulative_compaction_cnt(int64_t cnt) { _cumulative_compaction_cnt = cnt; }
184
0
    void set_full_compaction_cnt(int64_t cnt) { _full_compaction_cnt = cnt; }
185
    void set_cumulative_layer_point(int64_t new_point);
186
187
1
    int64_t last_cumu_compaction_failure_time() { return _last_cumu_compaction_failure_millis; }
188
3
    void set_last_cumu_compaction_failure_time(int64_t millis) {
189
3
        _last_cumu_compaction_failure_millis = millis;
190
3
    }
191
192
2
    int64_t last_base_compaction_failure_time() { return _last_base_compaction_failure_millis; }
193
3
    void set_last_base_compaction_failure_time(int64_t millis) {
194
3
        _last_base_compaction_failure_millis = millis;
195
3
    }
196
197
0
    int64_t last_full_compaction_failure_time() { return _last_full_compaction_failure_millis; }
198
0
    void set_last_full_compaction_failure_time(int64_t millis) {
199
0
        _last_full_compaction_failure_millis = millis;
200
0
    }
201
202
0
    int64_t last_cumu_compaction_success_time() { return _last_cumu_compaction_success_millis; }
203
0
    void set_last_cumu_compaction_success_time(int64_t millis) {
204
0
        _last_cumu_compaction_success_millis = millis;
205
0
    }
206
207
0
    int64_t last_base_compaction_success_time() { return _last_base_compaction_success_millis; }
208
0
    void set_last_base_compaction_success_time(int64_t millis) {
209
0
        _last_base_compaction_success_millis = millis;
210
0
    }
211
212
0
    int64_t last_full_compaction_success_time() { return _last_full_compaction_success_millis; }
213
0
    void set_last_full_compaction_success_time(int64_t millis) {
214
0
        _last_full_compaction_success_millis = millis;
215
0
    }
216
217
0
    int64_t last_cumu_compaction_schedule_time() { return _last_cumu_compaction_schedule_millis; }
218
0
    void set_last_cumu_compaction_schedule_time(int64_t millis) {
219
0
        _last_cumu_compaction_schedule_millis = millis;
220
0
    }
221
222
0
    int64_t last_base_compaction_schedule_time() { return _last_base_compaction_schedule_millis; }
223
0
    void set_last_base_compaction_schedule_time(int64_t millis) {
224
0
        _last_base_compaction_schedule_millis = millis;
225
0
    }
226
227
0
    int64_t last_full_compaction_schedule_time() { return _last_full_compaction_schedule_millis; }
228
0
    void set_last_full_compaction_schedule_time(int64_t millis) {
229
0
        _last_full_compaction_schedule_millis = millis;
230
0
    }
231
232
0
    void set_last_cumu_compaction_status(std::string status) {
233
0
        _last_cumu_compaction_status = std::move(status);
234
0
    }
235
236
0
    std::string get_last_cumu_compaction_status() { return _last_cumu_compaction_status; }
237
238
0
    void set_last_base_compaction_status(std::string status) {
239
0
        _last_base_compaction_status = std::move(status);
240
0
    }
241
242
0
    std::string get_last_base_compaction_status() { return _last_base_compaction_status; }
243
244
0
    void set_last_full_compaction_status(std::string status) {
245
0
        _last_full_compaction_status = std::move(status);
246
0
    }
247
248
0
    std::string get_last_full_compaction_status() { return _last_full_compaction_status; }
249
250
0
    int64_t alter_version() const { return _alter_version; }
251
2
    void set_alter_version(int64_t alter_version) { _alter_version = alter_version; }
252
253
    std::vector<RowsetSharedPtr> pick_candidate_rowsets_to_base_compaction();
254
255
7
    inline Version max_version() const {
256
7
        std::shared_lock rdlock(_meta_lock);
257
7
        return _tablet_meta->max_version();
258
7
    }
259
260
7
    int64_t base_size() const { return _base_size; }
261
262
    std::vector<RowsetSharedPtr> pick_candidate_rowsets_to_full_compaction();
263
    Result<RowsetSharedPtr> pick_a_rowset_for_index_change(int schema_version,
264
                                                           bool& is_base_rowset);
265
    Status check_rowset_schema_for_build_index(std::vector<TColumn>& columns, int schema_version);
266
267
0
    std::mutex& get_base_compaction_lock() { return _base_compaction_lock; }
268
0
    std::mutex& get_cumulative_compaction_lock() { return _cumulative_compaction_lock; }
269
270
    Result<std::unique_ptr<RowsetWriter>> create_transient_rowset_writer(
271
            const Rowset& rowset, std::shared_ptr<PartialUpdateInfo> partial_update_info,
272
            int64_t txn_expiration = 0) override;
273
274
    CalcDeleteBitmapExecutor* calc_delete_bitmap_executor() override;
275
276
    Status save_delete_bitmap(const TabletTxnInfo* txn_info, int64_t txn_id,
277
                              DeleteBitmapPtr delete_bitmap, RowsetWriter* rowset_writer,
278
                              const RowsetIdUnorderedSet& cur_rowset_ids, int64_t lock_id = -1,
279
                              int64_t next_visible_version = -1) override;
280
281
    Status save_delete_bitmap_to_ms(int64_t cur_version, int64_t txn_id,
282
                                    DeleteBitmapPtr delete_bitmap, int64_t lock_id,
283
                                    int64_t next_visible_version, RowsetSharedPtr rowset);
284
285
    Status calc_delete_bitmap_for_compaction(const std::vector<RowsetSharedPtr>& input_rowsets,
286
                                             const RowsetSharedPtr& output_rowset,
287
                                             const RowIdConversion& rowid_conversion,
288
                                             ReaderType compaction_type, int64_t merged_rows,
289
                                             int64_t filtered_rows, int64_t initiator,
290
                                             DeleteBitmapPtr& output_rowset_delete_bitmap,
291
                                             bool allow_delete_in_cumu_compaction,
292
                                             int64_t& get_delete_bitmap_lock_start_time);
293
294
    // Find the missed versions until the spec_version.
295
    //
296
    // for example:
297
    //     [0-4][5-5][8-8][9-9][14-14]
298
    // if spec_version = 12, it will return [6-7],[10-12]
299
    Versions calc_missed_versions(int64_t spec_version, Versions existing_versions) const override;
300
301
0
    std::mutex& get_rowset_update_lock() { return _rowset_update_lock; }
302
303
0
    bthread::Mutex& get_sync_meta_lock() { return _sync_meta_lock; }
304
305
94
    const auto& rowset_map() const { return _rs_version_map; }
306
307
    int64_t last_sync_time_s = 0;
308
    int64_t last_load_time_ms = 0;
309
    int64_t last_base_compaction_success_time_ms = 0;
310
    int64_t last_cumu_compaction_success_time_ms = 0;
311
    int64_t last_cumu_no_suitable_version_ms = 0;
312
    int64_t last_access_time_ms = 0;
313
314
    std::atomic<int64_t> local_read_time_us = 0;
315
    std::atomic<int64_t> remote_read_time_us = 0;
316
    std::atomic<int64_t> exec_compaction_time_us = 0;
317
318
    void build_tablet_report_info(TTabletInfo* tablet_info);
319
320
    // check that if the delete bitmap in delete bitmap cache has the same cardinality with the expected_delete_bitmap's
321
    Status check_delete_bitmap_cache(int64_t txn_id, DeleteBitmap* expected_delete_bitmap) override;
322
323
    void agg_delete_bitmap_for_compaction(int64_t start_version, int64_t end_version,
324
                                          const std::vector<RowsetSharedPtr>& pre_rowsets,
325
                                          DeleteBitmapPtr& new_delete_bitmap,
326
                                          std::map<std::string, int64_t>& pre_rowset_to_versions);
327
328
    bool need_remove_unused_rowsets();
329
330
    void add_unused_rowsets(const std::vector<RowsetSharedPtr>& rowsets);
331
    void remove_unused_rowsets();
332
333
    // For each given rowset not in active use, clears its file cache and returns its
334
    // ID, segment count, and index file names as RecycledRowsets entries.
335
    static std::vector<RecycledRowsets> recycle_cached_data(
336
            const std::vector<RowsetSharedPtr>& rowsets);
337
338
    // Add warmup state management
339
    WarmUpState get_rowset_warmup_state(RowsetId rowset_id);
340
    bool add_rowset_warmup_state(
341
            const RowsetMeta& rowset, WarmUpTriggerSource source,
342
            std::chrono::steady_clock::time_point start_tp = std::chrono::steady_clock::now());
343
    bool update_rowset_warmup_state_inverted_idx_num(WarmUpTriggerSource source, RowsetId rowset_id,
344
                                                     int64_t delta);
345
    bool update_rowset_warmup_state_inverted_idx_num_unlocked(WarmUpTriggerSource source,
346
                                                              RowsetId rowset_id, int64_t delta);
347
    WarmUpState complete_rowset_segment_warmup(WarmUpTriggerSource trigger_source,
348
                                               RowsetId rowset_id, Status status,
349
                                               int64_t segment_num, int64_t inverted_idx_num);
350
351
    bool is_rowset_warmed_up(const RowsetId& rowset_id) const;
352
353
    void add_warmed_up_rowset(const RowsetId& rowset_id);
354
355
5
    std::string rowset_warmup_digest() {
356
5
        std::string res;
357
104
        auto add_log = [&](const RowsetSharedPtr& rs) {
358
104
            auto tmp = fmt::format("{}{}", rs->rowset_id().to_string(), rs->version().to_string());
359
104
            if (_rowset_warm_up_states.contains(rs->rowset_id())) {
360
87
                tmp += fmt::format(
361
87
                        ", progress={}, segments_warmed_up={}/{}, inverted_idx_warmed_up={}/{}",
362
87
                        _rowset_warm_up_states.at(rs->rowset_id()).state.progress,
363
87
                        _rowset_warm_up_states.at(rs->rowset_id()).num_segments_warmed_up,
364
87
                        _rowset_warm_up_states.at(rs->rowset_id()).num_segments,
365
87
                        _rowset_warm_up_states.at(rs->rowset_id()).num_inverted_idx_warmed_up,
366
87
                        _rowset_warm_up_states.at(rs->rowset_id()).num_inverted_idx);
367
87
            }
368
104
            res += fmt::format("[{}],", tmp);
369
104
        };
370
5
        traverse_rowsets_unlocked(add_log, true);
371
5
        return res;
372
5
    }
373
374
private:
375
    // FIXME(plat1ko): No need to record base size if rowsets are ordered by version
376
    void update_base_size(const Rowset& rs);
377
378
    Status sync_if_not_running(SyncRowsetStats* stats = nullptr);
379
380
    bool add_rowset_warmup_state_unlocked(
381
            const RowsetMeta& rowset, WarmUpTriggerSource source,
382
            std::chrono::steady_clock::time_point start_tp = std::chrono::steady_clock::now());
383
384
    // used by capture_rs_reader_xxx functions
385
    bool rowset_is_warmed_up_unlocked(int64_t start_version, int64_t end_version);
386
387
    CloudStorageEngine& _engine;
388
389
    // this mutex MUST ONLY be used when sync meta
390
    bthread::Mutex _sync_meta_lock;
391
    // ATTENTION: lock order should be: _sync_meta_lock -> _meta_lock
392
393
    std::atomic<int64_t> _cumulative_point {-1};
394
    std::atomic<int64_t> _approximate_num_rowsets {-1};
395
    std::atomic<int64_t> _approximate_num_segments {-1};
396
    std::atomic<int64_t> _approximate_num_rows {-1};
397
    std::atomic<int64_t> _approximate_data_size {-1};
398
    std::atomic<int64_t> _approximate_cumu_num_rowsets {-1};
399
    // Number of sorted arrays (e.g. for rowset with N segments, if rowset is overlapping, delta is N, otherwise 1) after cumu point
400
    std::atomic<int64_t> _approximate_cumu_num_deltas {-1};
401
402
    // timestamp of last cumu compaction failure
403
    std::atomic<int64_t> _last_cumu_compaction_failure_millis;
404
    // timestamp of last base compaction failure
405
    std::atomic<int64_t> _last_base_compaction_failure_millis;
406
    // timestamp of last full compaction failure
407
    std::atomic<int64_t> _last_full_compaction_failure_millis;
408
    // timestamp of last cumu compaction success
409
    std::atomic<int64_t> _last_cumu_compaction_success_millis;
410
    // timestamp of last base compaction success
411
    std::atomic<int64_t> _last_base_compaction_success_millis;
412
    // timestamp of last full compaction success
413
    std::atomic<int64_t> _last_full_compaction_success_millis;
414
    // timestamp of last cumu compaction schedule time
415
    std::atomic<int64_t> _last_cumu_compaction_schedule_millis;
416
    // timestamp of last base compaction schedule time
417
    std::atomic<int64_t> _last_base_compaction_schedule_millis;
418
    // timestamp of last full compaction schedule time
419
    std::atomic<int64_t> _last_full_compaction_schedule_millis;
420
421
    std::string _last_cumu_compaction_status;
422
    std::string _last_base_compaction_status;
423
    std::string _last_full_compaction_status;
424
425
    int64_t _base_compaction_cnt = 0;
426
    int64_t _cumulative_compaction_cnt = 0;
427
    int64_t _full_compaction_cnt = 0;
428
    int64_t _max_version = -1;
429
    int64_t _base_size = 0;
430
    int64_t _alter_version = -1;
431
432
    std::mutex _base_compaction_lock;
433
    std::mutex _cumulative_compaction_lock;
434
435
    // To avoid multiple calc delete bitmap tasks on same (txn_id, tablet_id) with different
436
    // signatures being executed concurrently, we use _rowset_update_lock to serialize them
437
    mutable std::mutex _rowset_update_lock;
438
439
    // unused_rowsets, [start_version, end_version]
440
    std::mutex _gc_mutex;
441
    std::unordered_map<RowsetId, RowsetSharedPtr> _unused_rowsets;
442
    std::vector<std::pair<std::vector<RowsetId>, DeleteBitmapKeyRanges>> _unused_delete_bitmap;
443
444
    // for warm up states management
445
    struct RowsetWarmUpInfo {
446
        WarmUpState state;
447
        int64_t num_segments = 0;
448
        int64_t num_inverted_idx = 0;
449
        int64_t num_segments_warmed_up = 0;
450
        int64_t num_inverted_idx_warmed_up = 0;
451
        std::chrono::steady_clock::time_point start_tp;
452
453
18
        void done(int64_t num_segments, int64_t num_inverted_idx) {
454
18
            num_segments_warmed_up += num_segments;
455
18
            num_inverted_idx_warmed_up += num_inverted_idx;
456
18
            update_state();
457
18
        }
458
459
51
        bool has_finished() const {
460
51
            return (num_segments_warmed_up >= num_segments) &&
461
51
                   (num_inverted_idx_warmed_up >= num_inverted_idx);
462
51
        }
463
464
        void update_state();
465
    };
466
    std::unordered_map<RowsetId, RowsetWarmUpInfo> _rowset_warm_up_states;
467
468
    mutable std::shared_mutex _warmed_up_rowsets_mutex;
469
    std::unordered_set<RowsetId> _warmed_up_rowsets;
470
};
471
472
using CloudTabletSPtr = std::shared_ptr<CloudTablet>;
473
474
} // namespace doris