Coverage Report

Created: 2026-04-09 12:24

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/storage/txn/txn_manager.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 <gen_cpp/Types_types.h>
22
#include <gen_cpp/types.pb.h>
23
#include <stddef.h>
24
#include <stdint.h>
25
26
#include <boost/container/detail/std_fwd.hpp>
27
#include <map>
28
#include <memory>
29
#include <mutex>
30
#include <set>
31
#include <shared_mutex>
32
#include <unordered_map>
33
#include <unordered_set>
34
#include <utility>
35
#include <vector>
36
37
#include "common/status.h"
38
#include "core/block/block.h"
39
#include "runtime/memory/lru_cache_policy.h"
40
#include "storage/olap_common.h"
41
#include "storage/rowset/pending_rowset_helper.h"
42
#include "storage/rowset/rowset.h"
43
#include "storage/rowset/rowset_meta.h"
44
#include "storage/segment/segment.h"
45
#include "storage/segment/segment_writer.h"
46
#include "storage/tablet/tablet.h"
47
#include "storage/tablet/tablet_meta.h"
48
#include "util/time.h"
49
50
namespace doris {
51
class DeltaWriter;
52
class OlapMeta;
53
struct TabletPublishStatistics;
54
struct PartialUpdateInfo;
55
56
enum class TxnState {
57
    NOT_FOUND = 0,
58
    PREPARED = 1,
59
    COMMITTED = 2,
60
    ROLLEDBACK = 3,
61
    ABORTED = 4,
62
    DELETED = 5,
63
};
64
enum class PublishStatus { INIT = 0, PREPARE = 1, SUCCEED = 2 };
65
66
struct TxnPublishInfo {
67
    int64_t publish_version {-1};
68
    int64_t base_compaction_cnt {-1};
69
    int64_t cumulative_compaction_cnt {-1};
70
    int64_t cumulative_point {-1};
71
};
72
73
struct TabletTxnInfo {
74
    PUniqueId load_id;
75
    RowsetSharedPtr rowset;
76
    PendingRowsetGuard pending_rs_guard;
77
    bool unique_key_merge_on_write {false};
78
    DeleteBitmapPtr delete_bitmap;
79
    // records rowsets calc in commit txn
80
    RowsetIdUnorderedSet rowset_ids;
81
    int64_t creation_time;
82
    bool ingest {false};
83
    std::shared_ptr<PartialUpdateInfo> partial_update_info;
84
85
    // for cloud only, used to determine if a retry CloudTabletCalcDeleteBitmapTask
86
    // needs to re-calculate the delete bitmap
87
    std::shared_ptr<PublishStatus> publish_status;
88
    TxnPublishInfo publish_info;
89
90
    // for cloud only, used to calculate delete bitmap for txn load
91
    bool is_txn_load = false;
92
    std::vector<RowsetSharedPtr> invisible_rowsets;
93
    int64_t lock_id;
94
    int64_t next_visible_version;
95
96
    TxnState state {TxnState::PREPARED};
97
50.1k
    TabletTxnInfo() = default;
98
99
    TabletTxnInfo(PUniqueId load_id, RowsetSharedPtr rowset)
100
15.4k
            : load_id(std::move(load_id)),
101
15.4k
              rowset(std::move(rowset)),
102
15.4k
              creation_time(UnixSeconds()) {}
103
104
    TabletTxnInfo(PUniqueId load_id, RowsetSharedPtr rowset, bool ingest_arg)
105
15.3k
            : load_id(std::move(load_id)),
106
15.3k
              rowset(std::move(rowset)),
107
15.3k
              creation_time(UnixSeconds()),
108
15.3k
              ingest(ingest_arg) {}
109
110
    TabletTxnInfo(PUniqueId load_id, RowsetSharedPtr rowset, bool merge_on_write,
111
                  DeleteBitmapPtr delete_bitmap, RowsetIdUnorderedSet ids)
112
            : load_id(std::move(load_id)),
113
              rowset(std::move(rowset)),
114
              unique_key_merge_on_write(merge_on_write),
115
              delete_bitmap(std::move(delete_bitmap)),
116
              rowset_ids(std::move(ids)),
117
0
              creation_time(UnixSeconds()) {}
118
119
15.3k
    void prepare() { state = TxnState::PREPARED; }
120
15.4k
    void commit() { state = TxnState::COMMITTED; }
121
0
    void rollback() { state = TxnState::ROLLEDBACK; }
122
0
    void abort() {
123
0
        if (state == TxnState::PREPARED) {
124
0
            state = TxnState::ABORTED;
125
0
        }
126
0
    }
127
};
128
129
struct CommitTabletTxnInfo {
130
    TTransactionId transaction_id {0};
131
    TPartitionId partition_id {0};
132
    DeleteBitmapPtr delete_bitmap;
133
    RowsetIdUnorderedSet rowset_ids;
134
    std::shared_ptr<PartialUpdateInfo> partial_update_info;
135
};
136
137
using CommitTabletTxnInfoVec = std::vector<CommitTabletTxnInfo>;
138
139
// txn manager is used to manage mapping between tablet and txns
140
class TxnManager {
141
public:
142
    TxnManager(StorageEngine& engine, int32_t txn_map_shard_size, int32_t txn_shard_size);
143
144
347
    ~TxnManager() {
145
347
        delete[] _txn_tablet_maps;
146
347
        delete[] _txn_partition_maps;
147
347
        delete[] _txn_map_locks;
148
347
        delete[] _txn_mutex;
149
347
        delete[] _txn_tablet_delta_writer_map;
150
347
        delete[] _txn_tablet_delta_writer_map_locks;
151
347
    }
152
153
    class CacheValue : public LRUCacheValueBase {
154
    public:
155
        int64_t value;
156
    };
157
158
    // add a txn to manager
159
    // partition id is useful in publish version stage because version is associated with partition
160
    Status prepare_txn(TPartitionId partition_id, const Tablet& tablet,
161
                       TTransactionId transaction_id, const PUniqueId& load_id,
162
                       bool is_ingest = false);
163
    // most used for ut
164
    Status prepare_txn(TPartitionId partition_id, TTransactionId transaction_id,
165
                       TTabletId tablet_id, TabletUid tablet_uid, const PUniqueId& load_id,
166
                       bool is_ingest = false);
167
168
    Status commit_txn(TPartitionId partition_id, const Tablet& tablet,
169
                      TTransactionId transaction_id, const PUniqueId& load_id,
170
                      const RowsetSharedPtr& rowset_ptr, PendingRowsetGuard guard, bool is_recovery,
171
                      std::shared_ptr<PartialUpdateInfo> partial_update_info = nullptr);
172
173
    Status publish_txn(TPartitionId partition_id, const TabletSharedPtr& tablet,
174
                       TTransactionId transaction_id, const Version& version,
175
                       TabletPublishStatistics* stats,
176
                       std::shared_ptr<TabletTxnInfo>& extend_tablet_txn_info,
177
                       const int64_t commit_tso = -1);
178
179
    // delete the txn from manager if it is not committed(not have a valid rowset)
180
    Status rollback_txn(TPartitionId partition_id, const Tablet& tablet,
181
                        TTransactionId transaction_id);
182
183
    Status delete_txn(TPartitionId partition_id, const TabletSharedPtr& tablet,
184
                      TTransactionId transaction_id);
185
186
    Status commit_txn(OlapMeta* meta, TPartitionId partition_id, TTransactionId transaction_id,
187
                      TTabletId tablet_id, TabletUid tablet_uid, const PUniqueId& load_id,
188
                      const RowsetSharedPtr& rowset_ptr, PendingRowsetGuard guard, bool is_recovery,
189
                      std::shared_ptr<PartialUpdateInfo> partial_update_info = nullptr);
190
191
    // remove a txn from txn manager
192
    // not persist rowset meta because
193
    Status publish_txn(OlapMeta* meta, TPartitionId partition_id, TTransactionId transaction_id,
194
                       TTabletId tablet_id, TabletUid tablet_uid, const Version& version,
195
                       TabletPublishStatistics* stats,
196
                       std::shared_ptr<TabletTxnInfo>& extend_tablet_txn_info,
197
                       const int64_t commit_tso = -1);
198
199
    // only abort not committed txn
200
    void abort_txn(TPartitionId partition_id, TTransactionId transaction_id, TTabletId tablet_id,
201
                   TabletUid tablet_uid);
202
203
    // delete the txn from manager if it is not committed(not have a valid rowset)
204
    Status rollback_txn(TPartitionId partition_id, TTransactionId transaction_id,
205
                        TTabletId tablet_id, TabletUid tablet_uid);
206
207
    // remove the txn from txn manager
208
    // delete the related rowset if it is not null
209
    // delete rowset related data if it is not null
210
    Status delete_txn(OlapMeta* meta, TPartitionId partition_id, TTransactionId transaction_id,
211
                      TTabletId tablet_id, TabletUid tablet_uid);
212
213
    void get_tablet_related_txns(TTabletId tablet_id, TabletUid tablet_uid, int64_t* partition_id,
214
                                 std::set<int64_t>* transaction_ids);
215
216
    void get_txn_related_tablets(const TTransactionId transaction_id, TPartitionId partition_ids,
217
                                 std::map<TabletInfo, RowsetSharedPtr>* tablet_infos);
218
219
    void get_all_related_tablets(std::set<TabletInfo>* tablet_infos);
220
221
    // Get all expired txns and save them in expire_txn_map.
222
    // This is currently called before reporting all tablet info, to avoid iterating txn map for every tablets.
223
    void build_expire_txn_map(std::map<TabletInfo, std::vector<int64_t>>* expire_txn_map);
224
225
    void force_rollback_tablet_related_txns(OlapMeta* meta, TTabletId tablet_id,
226
                                            TabletUid tablet_uid);
227
228
    void get_partition_ids(const TTransactionId transaction_id,
229
                           std::vector<TPartitionId>* partition_ids);
230
231
    void add_txn_tablet_delta_writer(int64_t transaction_id, int64_t tablet_id,
232
                                     DeltaWriter* delta_writer);
233
    void clear_txn_tablet_delta_writer(int64_t transaction_id);
234
    void finish_slave_tablet_pull_rowset(int64_t transaction_id, int64_t tablet_id, int64_t node_id,
235
                                         bool is_succeed);
236
237
    void set_txn_related_delete_bitmap(TPartitionId partition_id, TTransactionId transaction_id,
238
                                       TTabletId tablet_id, TabletUid tablet_uid,
239
                                       bool unique_key_merge_on_write,
240
                                       DeleteBitmapPtr delete_bitmap,
241
                                       const RowsetIdUnorderedSet& rowset_ids,
242
                                       std::shared_ptr<PartialUpdateInfo> partial_update_info);
243
    void get_all_commit_tablet_txn_info_by_tablet(
244
            const Tablet& tablet, CommitTabletTxnInfoVec* commit_tablet_txn_info_vec);
245
246
    int64_t get_txn_by_tablet_version(int64_t tablet_id, int64_t version);
247
    void update_tablet_version_txn(int64_t tablet_id, int64_t version, int64_t txn_id);
248
249
    TxnState get_txn_state(TPartitionId partition_id, TTransactionId transaction_id,
250
                           TTabletId tablet_id, TabletUid tablet_uid);
251
252
    void remove_txn_tablet_info(TPartitionId partition_id, TTransactionId transaction_id,
253
                                TTabletId tablet_id, TabletUid tablet_uid);
254
255
private:
256
    using TxnKey = std::pair<int64_t, int64_t>; // partition_id, transaction_id;
257
258
    // Implement TxnKey hash function to support TxnKey as a key for `unordered_map`.
259
    struct TxnKeyHash {
260
        template <typename T, typename U>
261
114k
        size_t operator()(const std::pair<T, U>& e) const {
262
114k
            return std::hash<T>()(e.first) ^ std::hash<U>()(e.second);
263
114k
        }
264
    };
265
266
    // Implement TxnKey equal function to support TxnKey as a key for `unordered_map`.
267
    struct TxnKeyEqual {
268
        template <class T, typename U>
269
107k
        bool operator()(const std::pair<T, U>& l, const std::pair<T, U>& r) const {
270
107k
            return l.first == r.first && l.second == r.second;
271
107k
        }
272
    };
273
274
    using txn_tablet_map_t =
275
            std::unordered_map<TxnKey, std::map<TabletInfo, std::shared_ptr<TabletTxnInfo>>,
276
                               TxnKeyHash, TxnKeyEqual>;
277
    using txn_partition_map_t = std::unordered_map<int64_t, std::unordered_set<int64_t>>;
278
    using txn_tablet_delta_writer_map_t =
279
            std::unordered_map<int64_t, std::map<int64_t, DeltaWriter*>>;
280
281
    std::shared_mutex& _get_txn_map_lock(TTransactionId transactionId);
282
283
    txn_tablet_map_t& _get_txn_tablet_map(TTransactionId transactionId);
284
285
    txn_partition_map_t& _get_txn_partition_map(TTransactionId transactionId);
286
287
    inline std::shared_mutex& _get_txn_lock(TTransactionId transactionId);
288
289
    std::shared_mutex& _get_txn_tablet_delta_writer_map_lock(TTransactionId transactionId);
290
291
    txn_tablet_delta_writer_map_t& _get_txn_tablet_delta_writer_map(TTransactionId transactionId);
292
293
    // Insert or remove (transaction_id, partition_id) from _txn_partition_map
294
    // get _txn_map_lock before calling.
295
    void _insert_txn_partition_map_unlocked(int64_t transaction_id, int64_t partition_id);
296
    void _clear_txn_partition_map_unlocked(int64_t transaction_id, int64_t partition_id);
297
298
    void _remove_txn_tablet_info_unlocked(TPartitionId partition_id, TTransactionId transaction_id,
299
                                          TTabletId tablet_id, TabletUid tablet_uid,
300
                                          std::lock_guard<std::shared_mutex>& txn_lock,
301
                                          std::lock_guard<std::shared_mutex>& wrlock);
302
303
    class TabletVersionCache : public LRUCachePolicy {
304
    public:
305
        TabletVersionCache(size_t capacity)
306
350
                : LRUCachePolicy(CachePolicy::CacheType::TABLET_VERSION_CACHE, capacity,
307
350
                                 LRUCacheType::NUMBER, /*sweeptime*/ -1,
308
350
                                 /*num_shards*/ 32,
309
350
                                 /*element_count_capacity*/ 0, /*enable_prune*/ false,
310
350
                                 /*is_lru_k*/ false) {}
311
    };
312
313
private:
314
    StorageEngine& _engine;
315
316
    const int32_t _txn_map_shard_size;
317
318
    const int32_t _txn_shard_size;
319
320
    // _txn_map_locks[i] protect _txn_tablet_maps[i], i=0,1,2...,and i < _txn_map_shard_size
321
    txn_tablet_map_t* _txn_tablet_maps = nullptr;
322
    // transaction_id -> corresponding partition ids
323
    // This is mainly for the clear txn task received from FE, which may only has transaction id,
324
    // so we need this map to find out which partitions are corresponding to a transaction id.
325
    // The _txn_partition_maps[i] should be constructed/deconstructed/modified alongside with '_txn_tablet_maps[i]'
326
    txn_partition_map_t* _txn_partition_maps = nullptr;
327
328
    std::shared_mutex* _txn_map_locks = nullptr;
329
330
    std::shared_mutex* _txn_mutex = nullptr;
331
332
    txn_tablet_delta_writer_map_t* _txn_tablet_delta_writer_map = nullptr;
333
    std::unique_ptr<TabletVersionCache> _tablet_version_cache;
334
    std::shared_mutex* _txn_tablet_delta_writer_map_locks = nullptr;
335
    DISALLOW_COPY_AND_ASSIGN(TxnManager);
336
}; // TxnManager
337
338
84.0k
inline std::shared_mutex& TxnManager::_get_txn_map_lock(TTransactionId transactionId) {
339
84.0k
    return _txn_map_locks[transactionId & (_txn_map_shard_size - 1)];
340
84.0k
}
341
342
84.0k
inline TxnManager::txn_tablet_map_t& TxnManager::_get_txn_tablet_map(TTransactionId transactionId) {
343
84.0k
    return _txn_tablet_maps[transactionId & (_txn_map_shard_size - 1)];
344
84.0k
}
345
346
inline TxnManager::txn_partition_map_t& TxnManager::_get_txn_partition_map(
347
48.5k
        TTransactionId transactionId) {
348
48.5k
    return _txn_partition_maps[transactionId & (_txn_map_shard_size - 1)];
349
48.5k
}
350
351
50.5k
inline std::shared_mutex& TxnManager::_get_txn_lock(TTransactionId transactionId) {
352
50.5k
    return _txn_mutex[transactionId & (_txn_shard_size - 1)];
353
50.5k
}
354
355
inline std::shared_mutex& TxnManager::_get_txn_tablet_delta_writer_map_lock(
356
0
        TTransactionId transactionId) {
357
0
    return _txn_tablet_delta_writer_map_locks[transactionId & (_txn_map_shard_size - 1)];
358
0
}
359
360
inline TxnManager::txn_tablet_delta_writer_map_t& TxnManager::_get_txn_tablet_delta_writer_map(
361
0
        TTransactionId transactionId) {
362
0
    return _txn_tablet_delta_writer_map[transactionId & (_txn_map_shard_size - 1)];
363
0
}
364
365
} // namespace doris