Coverage Report

Created: 2025-07-23 16:39

/root/doris/be/src/olap/base_tablet.h
Line
Count
Source (jump to first uncovered line)
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 <gen_cpp/olap_common.pb.h>
21
22
#include <memory>
23
#include <shared_mutex>
24
#include <string>
25
26
#include "common/status.h"
27
#include "olap/iterators.h"
28
#include "olap/olap_common.h"
29
#include "olap/partial_update_info.h"
30
#include "olap/rowset/segment_v2/segment.h"
31
#include "olap/tablet_fwd.h"
32
#include "olap/tablet_meta.h"
33
#include "olap/tablet_schema.h"
34
#include "olap/version_graph.h"
35
#include "util/metrics.h"
36
37
namespace doris {
38
struct RowSetSplits;
39
struct RowsetWriterContext;
40
class RowsetWriter;
41
class CalcDeleteBitmapToken;
42
class SegmentCacheHandle;
43
class RowIdConversion;
44
struct PartialUpdateInfo;
45
class PartialUpdateReadPlan;
46
struct CaptureRowsetOps;
47
struct CaptureRowsetResult;
48
struct TabletReadSource;
49
class FixedReadPlan;
50
51
struct TabletWithVersion {
52
    BaseTabletSPtr tablet;
53
    int64_t version;
54
};
55
56
enum class CompactionStage { NOT_SCHEDULED, PENDING, EXECUTING };
57
58
// Base class for all tablet classes
59
class BaseTablet {
60
public:
61
    explicit BaseTablet(TabletMetaSharedPtr tablet_meta);
62
    virtual ~BaseTablet();
63
    BaseTablet(const BaseTablet&) = delete;
64
    BaseTablet& operator=(const BaseTablet&) = delete;
65
66
9.35k
    TabletState tablet_state() const { return _tablet_meta->tablet_state(); }
67
    Status set_tablet_state(TabletState state);
68
3
    int64_t table_id() const { return _tablet_meta->table_id(); }
69
0
    int64_t index_id() const { return _tablet_meta->index_id(); }
70
950
    int64_t partition_id() const { return _tablet_meta->partition_id(); }
71
18.0k
    int64_t tablet_id() const { return _tablet_meta->tablet_id(); }
72
1.51k
    int32_t schema_hash() const { return _tablet_meta->schema_hash(); }
73
0
    size_t row_size() const { return _tablet_meta->tablet_schema()->row_size(); }
74
1.28k
    KeysType keys_type() const { return _tablet_meta->tablet_schema()->keys_type(); }
75
128
    size_t num_key_columns() const { return _tablet_meta->tablet_schema()->num_key_columns(); }
76
341
    int64_t ttl_seconds() const { return _tablet_meta->ttl_seconds(); }
77
18
    std::mutex& get_schema_change_lock() { return _schema_change_lock; }
78
0
    CompressKind compress_kind() const { return _tablet_meta->tablet_schema()->compress_kind(); }
79
1.53k
    bool enable_unique_key_merge_on_write() const {
80
1.53k
#ifdef BE_TEST
81
1.53k
        if (_tablet_meta == nullptr) {
  Branch (81:13): [True: 0, False: 1.53k]
82
0
            return false;
83
0
        }
84
1.53k
#endif
85
1.53k
        return _tablet_meta->enable_unique_key_merge_on_write();
86
1.53k
    }
87
88
    // Property encapsulated in TabletMeta
89
2.66k
    const TabletMetaSharedPtr& tablet_meta() { return _tablet_meta; }
90
91
    int32 max_version_config();
92
93
    // FIXME(plat1ko): It is not appropriate to expose this lock
94
66
    std::shared_mutex& get_header_lock() { return _meta_lock; }
95
96
    void update_max_version_schema(const TabletSchemaSPtr& tablet_schema);
97
98
    Status update_by_least_common_schema(const TabletSchemaSPtr& update_schema);
99
100
11.5k
    TabletSchemaSPtr tablet_schema() const {
101
11.5k
        std::shared_lock rlock(_meta_lock);
102
11.5k
        return _max_version_schema;
103
11.5k
    }
104
105
0
    void set_alter_failed(bool alter_failed) { _alter_failed = alter_failed; }
106
0
    bool is_alter_failed() { return _alter_failed; }
107
108
    virtual std::string tablet_path() const = 0;
109
110
    virtual bool exceed_version_limit(int32_t limit) = 0;
111
112
    virtual Result<std::unique_ptr<RowsetWriter>> create_rowset_writer(RowsetWriterContext& context,
113
                                                                       bool vertical) = 0;
114
115
    virtual Status capture_rs_readers(const Version& spec_version,
116
                                      std::vector<RowSetSplits>* rs_splits,
117
                                      bool skip_missing_version) = 0;
118
119
    virtual size_t tablet_footprint() = 0;
120
121
    // this method just return the compaction sum on each rowset
122
    // note(tsy): we should unify the compaction score calculation finally
123
    uint32_t get_real_compaction_score() const;
124
125
    // MUST hold shared meta lock
126
    Status capture_rs_readers_unlocked(const Versions& version_path,
127
                                       std::vector<RowSetSplits>* rs_splits) const;
128
129
    // _rs_version_map and _stale_rs_version_map should be protected by _meta_lock
130
    // The caller must call hold _meta_lock when call this three function.
131
    RowsetSharedPtr get_rowset_by_version(const Version& version, bool find_is_stale = false) const;
132
    RowsetSharedPtr get_stale_rowset_by_version(const Version& version) const;
133
    RowsetSharedPtr get_rowset_with_max_version() const;
134
135
    Status get_all_rs_id(int64_t max_version, RowsetIdUnorderedSet* rowset_ids) const;
136
    Status get_all_rs_id_unlocked(int64_t max_version, RowsetIdUnorderedSet* rowset_ids) const;
137
138
    // Get the missed versions until the spec_version.
139
    Versions get_missed_versions(int64_t spec_version) const;
140
    Versions get_missed_versions_unlocked(int64_t spec_version) const;
141
142
    void generate_tablet_meta_copy(TabletMeta& new_tablet_meta) const;
143
    void generate_tablet_meta_copy_unlocked(TabletMeta& new_tablet_meta) const;
144
145
36
    virtual int64_t max_version_unlocked() const { return _tablet_meta->max_version().second; }
146
147
    static TabletSchemaSPtr tablet_schema_with_merged_max_schema_version(
148
            const std::vector<RowsetMetaSharedPtr>& rowset_metas);
149
150
    Status get_compaction_schema(const std::vector<RowsetMetaSharedPtr>& rowset_metas,
151
                                 TabletSchemaSPtr& target_schema);
152
153
    ////////////////////////////////////////////////////////////////////////////
154
    // begin MoW functions
155
    ////////////////////////////////////////////////////////////////////////////
156
    std::vector<RowsetSharedPtr> get_rowset_by_ids(
157
            const RowsetIdUnorderedSet* specified_rowset_ids);
158
159
    // Lookup a row with TupleDescriptor and fill Block
160
    Status lookup_row_data(const Slice& encoded_key, const RowLocation& row_location,
161
                           RowsetSharedPtr rowset, const TupleDescriptor* desc,
162
                           OlapReaderStatistics& stats, std::string& values,
163
                           bool write_to_cache = false);
164
    // Lookup the row location of `encoded_key`, the function sets `row_location` on success.
165
    // NOTE: the method only works in unique key model with primary key index, you will got a
166
    //       not supported error in other data model.
167
    Status lookup_row_key(const Slice& encoded_key, TabletSchema* latest_schema, bool with_seq_col,
168
                          const std::vector<RowsetSharedPtr>& specified_rowsets,
169
                          RowLocation* row_location, uint32_t version,
170
                          std::vector<std::unique_ptr<SegmentCacheHandle>>& segment_caches,
171
                          RowsetSharedPtr* rowset = nullptr, bool with_rowid = true,
172
                          std::string* encoded_seq_value = nullptr,
173
                          OlapReaderStatistics* stats = nullptr);
174
175
    // calc delete bitmap when flush memtable, use a fake version to calc
176
    // For example, cur max version is 5, and we use version 6 to calc but
177
    // finally this rowset publish version with 8, we should make up data
178
    // for rowset 6-7. Also, if a compaction happens between commit_txn and
179
    // publish_txn, we should remove compaction input rowsets' delete_bitmap
180
    // and build newly generated rowset's delete_bitmap
181
    static Status calc_delete_bitmap(const BaseTabletSPtr& tablet, RowsetSharedPtr rowset,
182
                                     const std::vector<segment_v2::SegmentSharedPtr>& segments,
183
                                     const std::vector<RowsetSharedPtr>& specified_rowsets,
184
                                     DeleteBitmapPtr delete_bitmap, int64_t version,
185
                                     CalcDeleteBitmapToken* token,
186
                                     RowsetWriter* rowset_writer = nullptr);
187
188
    Status calc_segment_delete_bitmap(RowsetSharedPtr rowset,
189
                                      const segment_v2::SegmentSharedPtr& seg,
190
                                      const std::vector<RowsetSharedPtr>& specified_rowsets,
191
                                      DeleteBitmapPtr delete_bitmap, int64_t end_version,
192
                                      RowsetWriter* rowset_writer);
193
194
    Status calc_delete_bitmap_between_segments(
195
            const RowsetId& rowset_id, const std::vector<segment_v2::SegmentSharedPtr>& segments,
196
            DeleteBitmapPtr delete_bitmap);
197
198
    static Status commit_phase_update_delete_bitmap(
199
            const BaseTabletSPtr& tablet, const RowsetSharedPtr& rowset,
200
            RowsetIdUnorderedSet& pre_rowset_ids, DeleteBitmapPtr delete_bitmap,
201
            const std::vector<segment_v2::SegmentSharedPtr>& segments, int64_t txn_id,
202
            CalcDeleteBitmapToken* token, RowsetWriter* rowset_writer = nullptr);
203
204
    static void add_sentinel_mark_to_delete_bitmap(DeleteBitmap* delete_bitmap,
205
                                                   const RowsetIdUnorderedSet& rowsetids);
206
207
    Status check_delete_bitmap_correctness(DeleteBitmapPtr delete_bitmap, int64_t max_version,
208
                                           int64_t txn_id, const RowsetIdUnorderedSet& rowset_ids,
209
                                           std::vector<RowsetSharedPtr>* rowsets = nullptr);
210
211
    static const signed char* get_delete_sign_column_data(const vectorized::Block& block,
212
                                                          size_t rows_at_least = 0);
213
214
    static Status generate_default_value_block(const TabletSchema& schema,
215
                                               const std::vector<uint32_t>& cids,
216
                                               const std::vector<std::string>& default_values,
217
                                               const vectorized::Block& ref_block,
218
                                               vectorized::Block& default_value_block);
219
220
    static Status generate_new_block_for_partial_update(
221
            TabletSchemaSPtr rowset_schema, const PartialUpdateInfo* partial_update_info,
222
            const FixedReadPlan& read_plan_ori, const FixedReadPlan& read_plan_update,
223
            const std::map<RowsetId, RowsetSharedPtr>& rsid_to_rowset,
224
            vectorized::Block* output_block);
225
226
    static Status generate_new_block_for_flexible_partial_update(
227
            TabletSchemaSPtr rowset_schema, const PartialUpdateInfo* partial_update_info,
228
            std::set<uint32_t>& rids_be_overwritten, const FixedReadPlan& read_plan_ori,
229
            const FixedReadPlan& read_plan_update,
230
            const std::map<RowsetId, RowsetSharedPtr>& rsid_to_rowset,
231
            vectorized::Block* output_block);
232
233
    // We use the TabletSchema from the caller because the TabletSchema in the rowset'meta
234
    // may be outdated due to schema change. Also note that the the cids should indicate the indexes
235
    // of the columns in the TabletSchema passed in.
236
    static Status fetch_value_through_row_column(RowsetSharedPtr input_rowset,
237
                                                 const TabletSchema& tablet_schema, uint32_t segid,
238
                                                 const std::vector<uint32_t>& rowids,
239
                                                 const std::vector<uint32_t>& cids,
240
                                                 vectorized::Block& block);
241
242
    static Status fetch_value_by_rowids(RowsetSharedPtr input_rowset, uint32_t segid,
243
                                        const std::vector<uint32_t>& rowids,
244
                                        const TabletColumn& tablet_column,
245
                                        vectorized::MutableColumnPtr& dst);
246
247
    virtual Result<std::unique_ptr<RowsetWriter>> create_transient_rowset_writer(
248
            const Rowset& rowset, std::shared_ptr<PartialUpdateInfo> partial_update_info,
249
            int64_t txn_expiration = 0) = 0;
250
251
    static Status update_delete_bitmap(const BaseTabletSPtr& self, TabletTxnInfo* txn_info,
252
                                       int64_t txn_id, int64_t txn_expiration = 0);
253
    virtual Status save_delete_bitmap(const TabletTxnInfo* txn_info, int64_t txn_id,
254
                                      DeleteBitmapPtr delete_bitmap, RowsetWriter* rowset_writer,
255
                                      const RowsetIdUnorderedSet& cur_rowset_ids,
256
                                      int64_t next_visible_version = -1) = 0;
257
    virtual CalcDeleteBitmapExecutor* calc_delete_bitmap_executor() = 0;
258
259
    void calc_compaction_output_rowset_delete_bitmap(
260
            const std::vector<RowsetSharedPtr>& input_rowsets,
261
            const RowIdConversion& rowid_conversion, uint64_t start_version, uint64_t end_version,
262
            std::set<RowLocation>* missed_rows,
263
            std::map<RowsetSharedPtr, std::list<std::pair<RowLocation, RowLocation>>>* location_map,
264
            const DeleteBitmap& input_delete_bitmap, DeleteBitmap* output_rowset_delete_bitmap);
265
266
    Status check_rowid_conversion(
267
            RowsetSharedPtr dst_rowset,
268
            const std::map<RowsetSharedPtr, std::list<std::pair<RowLocation, RowLocation>>>&
269
                    location_map);
270
271
    static Status update_delete_bitmap_without_lock(
272
            const BaseTabletSPtr& self, const RowsetSharedPtr& rowset,
273
            const std::vector<RowsetSharedPtr>* specified_base_rowsets = nullptr);
274
275
    using DeleteBitmapKeyRanges =
276
            std::vector<std::tuple<DeleteBitmap::BitmapKey, DeleteBitmap::BitmapKey>>;
277
    void agg_delete_bitmap_for_stale_rowsets(
278
            Version version, DeleteBitmapKeyRanges& remove_delete_bitmap_key_ranges);
279
    void check_agg_delete_bitmap_for_stale_rowsets(int64_t& useless_rowset_count,
280
                                                   int64_t& useless_rowset_version_count);
281
    ////////////////////////////////////////////////////////////////////////////
282
    // end MoW functions
283
    ////////////////////////////////////////////////////////////////////////////
284
285
    RowsetSharedPtr get_rowset(const RowsetId& rowset_id);
286
287
    std::vector<RowsetSharedPtr> get_snapshot_rowset(bool include_stale_rowset = false) const;
288
289
    virtual void clear_cache() = 0;
290
291
    // Find the first consecutive empty rowsets. output->size() >= limit
292
    void calc_consecutive_empty_rowsets(std::vector<RowsetSharedPtr>* empty_rowsets,
293
                                        const std::vector<RowsetSharedPtr>& candidate_rowsets,
294
                                        int64_t limit);
295
296
    // Return the merged schema of all rowsets
297
0
    virtual TabletSchemaSPtr merged_tablet_schema() const {
298
0
        std::shared_lock rlock(_meta_lock);
299
0
        return _max_version_schema;
300
0
    }
301
302
    TabletSchemaSPtr calculate_variant_extended_schema() const;
303
304
    void traverse_rowsets(std::function<void(const RowsetSharedPtr&)> visitor,
305
11
                          bool include_stale = false) {
306
11
        std::shared_lock rlock(_meta_lock);
307
62
        for (auto& [v, rs] : _rs_version_map) {
  Branch (307:28): [True: 62, False: 11]
308
62
            visitor(rs);
309
62
        }
310
11
        if (!include_stale) return;
  Branch (310:13): [True: 1, False: 10]
311
10
        for (auto& [v, rs] : _stale_rs_version_map) {
  Branch (311:28): [True: 0, False: 10]
312
0
            visitor(rs);
313
0
        }
314
10
    }
315
316
    Status calc_file_crc(uint32_t* crc_value, int64_t start_version, int64_t end_version,
317
                         int32_t* rowset_count, int64_t* file_count);
318
319
    Status show_nested_index_file(std::string* json_meta);
320
321
12.4k
    TabletUid tablet_uid() const { return _tablet_meta->tablet_uid(); }
322
561
    TabletInfo get_tablet_info() const { return TabletInfo(tablet_id(), tablet_uid()); }
323
324
    void get_base_rowset_delete_bitmap_count(
325
            uint64_t* max_base_rowset_delete_bitmap_score,
326
            int64_t* max_base_rowset_delete_bitmap_score_tablet_id);
327
328
3
    virtual Status check_delete_bitmap_cache(int64_t txn_id, DeleteBitmap* expected_delete_bitmap) {
329
3
        return Status::OK();
330
3
    }
331
332
    [[nodiscard]] Result<CaptureRowsetResult> capture_consistent_rowsets_unlocked(
333
            const Version& version_range, const CaptureRowsetOps& options) const;
334
335
    [[nodiscard]] Result<std::vector<Version>> capture_consistent_versions_unlocked(
336
            const Version& version_range, const CaptureRowsetOps& options) const;
337
338
    [[nodiscard]] Result<std::vector<RowSetSplits>> capture_rs_readers_unlocked(
339
            const Version& version_range, const CaptureRowsetOps& options) const;
340
341
    [[nodiscard]] Result<TabletReadSource> capture_read_source(const Version& version_range,
342
                                                               const CaptureRowsetOps& options);
343
344
    Result<CaptureRowsetResult> _remote_capture_rowsets(const Version& version_range) const;
345
346
protected:
347
    // Find the missed versions until the spec_version.
348
    //
349
    // for example:
350
    //     [0-4][5-5][8-8][9-9][14-14]
351
    // for cloud, if spec_version = 12, it will return [6-7],[10-12]
352
    // for local, if spec_version = 12, it will return [6, 6], [7, 7], [10, 10], [11, 11], [12, 12]
353
    virtual Versions calc_missed_versions(int64_t spec_version,
354
                                          Versions existing_versions) const = 0;
355
356
    void _print_missed_versions(const Versions& missed_versions) const;
357
    bool _reconstruct_version_tracker_if_necessary();
358
359
    static void _rowset_ids_difference(const RowsetIdUnorderedSet& cur,
360
                                       const RowsetIdUnorderedSet& pre,
361
                                       RowsetIdUnorderedSet* to_add, RowsetIdUnorderedSet* to_del);
362
363
    Status sort_block(vectorized::Block& in_block, vectorized::Block& output_block);
364
365
    mutable std::shared_mutex _meta_lock;
366
    TimestampedVersionTracker _timestamped_version_tracker;
367
    // After version 0.13, all newly created rowsets are saved in _rs_version_map.
368
    // And if rowset being compacted, the old rowsets will be saved in _stale_rs_version_map;
369
    std::unordered_map<Version, RowsetSharedPtr, HashOfVersion> _rs_version_map;
370
    // This variable _stale_rs_version_map is used to record these rowsets which are be compacted.
371
    // These _stale rowsets are been removed when rowsets' pathVersion is expired,
372
    // this policy is judged and computed by TimestampedVersionTracker.
373
    std::unordered_map<Version, RowsetSharedPtr, HashOfVersion> _stale_rs_version_map;
374
    const TabletMetaSharedPtr _tablet_meta;
375
    TabletSchemaSPtr _max_version_schema;
376
377
    // `_alter_failed` is used to indicate whether the tablet failed to perform a schema change
378
    std::atomic<bool> _alter_failed = false;
379
380
    // metrics of this tablet
381
    std::shared_ptr<MetricEntity> _metric_entity;
382
383
protected:
384
    std::mutex _schema_change_lock;
385
386
public:
387
    IntCounter* query_scan_bytes = nullptr;
388
    IntCounter* query_scan_rows = nullptr;
389
    IntCounter* query_scan_count = nullptr;
390
    IntCounter* flush_bytes = nullptr;
391
    IntCounter* flush_finish_count = nullptr;
392
    std::atomic<int64_t> published_count = 0;
393
    std::atomic<int64_t> read_block_count = 0;
394
    std::atomic<int64_t> write_count = 0;
395
    std::atomic<int64_t> compaction_count = 0;
396
397
    CompactionStage compaction_stage = CompactionStage::NOT_SCHEDULED;
398
    std::mutex sample_info_lock;
399
    std::vector<CompactionSampleInfo> sample_infos;
400
    Status last_compaction_status = Status::OK();
401
};
402
403
struct CaptureRowsetOps {
404
    bool skip_missing_versions = false;
405
    bool quiet = false;
406
    bool include_stale_rowsets = true;
407
    bool enable_fetch_rowsets_from_peers = false;
408
};
409
410
struct CaptureRowsetResult {
411
    std::vector<RowsetSharedPtr> rowsets;
412
    std::shared_ptr<DeleteBitmap> delete_bitmap;
413
};
414
415
struct TabletReadSource {
416
    std::vector<RowSetSplits> rs_splits;
417
    std::vector<RowsetMetaSharedPtr> delete_predicates;
418
    std::shared_ptr<DeleteBitmap> delete_bitmap;
419
    // Fill delete predicates with `rs_splits`
420
    void fill_delete_predicates();
421
};
422
423
} /* namespace doris */