Coverage Report

Created: 2026-10-27 17:54

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/vertical_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 OlapMeta;
52
class PChangelogWriteColumnMappings;
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
// The changelog rowset and its independent changelog tablet, carried through commit and publish.
67
struct ChangelogTxnInfo {
68
    std::shared_ptr<const PChangelogWriteColumnMappings> column_mappings;
69
    RowsetSharedPtr rowset;
70
    BaseTabletSPtr tablet;
71
    // Delete bitmap deltas that should be applied to the independent changelog tablet.
72
    DeleteBitmapPtr delete_bitmap;
73
};
74
75
struct TxnPublishInfo {
76
    int64_t publish_version {-1};
77
    int64_t base_compaction_cnt {-1};
78
    int64_t cumulative_compaction_cnt {-1};
79
    int64_t cumulative_point {-1};
80
};
81
82
struct TabletTxnInfo {
83
    PUniqueId load_id;
84
    RowsetSharedPtr rowset;
85
    // The changelog tablet is attached while PREPARED; its rowset is filled at commit.
86
    ChangelogTxnInfo attach_changelog;
87
    PendingRowsetGuard pending_rs_guard;
88
    bool unique_key_merge_on_write {false};
89
    DeleteBitmapPtr delete_bitmap;
90
    // records rowsets calc in commit txn
91
    RowsetIdUnorderedSet rowset_ids;
92
    int64_t creation_time;
93
    bool ingest {false};
94
    std::shared_ptr<PartialUpdateInfo> partial_update_info;
95
96
    // for cloud only, used to determine if a retry CloudTabletCalcDeleteBitmapTask
97
    // needs to re-calculate the delete bitmap
98
    std::shared_ptr<PublishStatus> publish_status;
99
    TxnPublishInfo publish_info;
100
101
    // for cloud only, used to calculate delete bitmap for txn load
102
    bool is_txn_load = false;
103
    std::vector<RowsetSharedPtr> invisible_rowsets;
104
    int64_t lock_id;
105
    int64_t next_visible_version;
106
107
    TxnState state {TxnState::PREPARED};
108
23.8k
    TabletTxnInfo() = default;
109
110
    TabletTxnInfo(PUniqueId load_id, RowsetSharedPtr rowset)
111
432
            : load_id(std::move(load_id)),
112
432
              rowset(std::move(rowset)),
113
432
              creation_time(UnixSeconds()) {}
114
115
    TabletTxnInfo(PUniqueId load_id, RowsetSharedPtr rowset, bool ingest_arg)
116
297
            : load_id(std::move(load_id)),
117
297
              rowset(std::move(rowset)),
118
297
              creation_time(UnixSeconds()),
119
297
              ingest(ingest_arg) {}
120
121
    TabletTxnInfo(PUniqueId load_id, RowsetSharedPtr rowset, bool merge_on_write,
122
                  DeleteBitmapPtr delete_bitmap, RowsetIdUnorderedSet ids)
123
            : load_id(std::move(load_id)),
124
              rowset(std::move(rowset)),
125
              unique_key_merge_on_write(merge_on_write),
126
              delete_bitmap(std::move(delete_bitmap)),
127
              rowset_ids(std::move(ids)),
128
0
              creation_time(UnixSeconds()) {}
129
130
297
    void prepare() { state = TxnState::PREPARED; }
131
431
    void commit() { state = TxnState::COMMITTED; }
132
0
    void rollback() { state = TxnState::ROLLEDBACK; }
133
0
    void abort() {
134
0
        if (state == TxnState::PREPARED) {
135
0
            state = TxnState::ABORTED;
136
0
        }
137
0
    }
138
};
139
140
struct CommitTabletTxnInfo {
141
    TTransactionId transaction_id {0};
142
    TPartitionId partition_id {0};
143
    DeleteBitmapPtr delete_bitmap;
144
    RowsetIdUnorderedSet rowset_ids;
145
    std::shared_ptr<PartialUpdateInfo> partial_update_info;
146
};
147
148
using CommitTabletTxnInfoVec = std::vector<CommitTabletTxnInfo>;
149
150
// txn manager is used to manage mapping between tablet and txns
151
class TxnManager {
152
public:
153
    TxnManager(StorageEngine& engine, int32_t txn_map_shard_size, int32_t txn_shard_size);
154
155
810
    ~TxnManager() {
156
810
        delete[] _txn_tablet_maps;
157
810
        delete[] _txn_partition_maps;
158
810
        delete[] _txn_map_locks;
159
810
        delete[] _txn_mutex;
160
810
    }
161
162
    class CacheValue : public LRUCacheValueBase {
163
    public:
164
        int64_t value;
165
    };
166
167
    // add a txn to manager
168
    // partition id is useful in publish version stage because version is associated with partition
169
    Status prepare_txn(TPartitionId partition_id, const Tablet& tablet,
170
                       TTransactionId transaction_id, const PUniqueId& load_id,
171
                       bool is_ingest = false);
172
    // most used for ut
173
    Status prepare_txn(TPartitionId partition_id, TTransactionId transaction_id,
174
                       TTabletId tablet_id, TabletUid tablet_uid, const PUniqueId& load_id,
175
                       bool is_ingest = false);
176
177
    // Internal: attach the independent changelog tablet to an existing base-tablet transaction
178
    // before commit, so tablet lifecycle operations can drain the whole group transaction.
179
    Status attach_changelog_tablet_to_txn(TPartitionId partition_id, TTransactionId transaction_id,
180
                                          const TabletInfo& base_tablet_info,
181
                                          const BaseTabletSPtr& changelog_tablet);
182
183
    Status commit_txn(TPartitionId partition_id, const Tablet& tablet,
184
                      TTransactionId transaction_id, const PUniqueId& load_id,
185
                      const RowsetSharedPtr& rowset_ptr, PendingRowsetGuard guard, bool is_recovery,
186
                      std::shared_ptr<PartialUpdateInfo> partial_update_info = nullptr,
187
                      const ChangelogTxnInfo& attach_changelog = {});
188
189
    Status publish_txn(
190
            TPartitionId partition_id, const TabletSharedPtr& tablet, TTransactionId transaction_id,
191
            const Version& version, TabletPublishStatistics* stats,
192
            std::shared_ptr<TabletTxnInfo>& extend_tablet_txn_info, const int64_t commit_tso = -1,
193
            std::shared_ptr<const PChangelogWriteColumnMappings> column_mappings = nullptr);
194
195
    // delete the txn from manager if it is not committed(not have a valid rowset)
196
    Status rollback_txn(TPartitionId partition_id, const Tablet& tablet,
197
                        TTransactionId transaction_id);
198
199
    Status delete_txn(TPartitionId partition_id, const TabletSharedPtr& tablet,
200
                      TTransactionId transaction_id);
201
202
    Status commit_txn(OlapMeta* meta, TPartitionId partition_id, TTransactionId transaction_id,
203
                      TTabletId tablet_id, TabletUid tablet_uid, const PUniqueId& load_id,
204
                      const RowsetSharedPtr& rowset_ptr, PendingRowsetGuard guard, bool is_recovery,
205
                      std::shared_ptr<PartialUpdateInfo> partial_update_info = nullptr,
206
                      const ChangelogTxnInfo& attach_changelog = {});
207
208
    // remove a txn from txn manager
209
    // not persist rowset meta because
210
    Status publish_txn(
211
            OlapMeta* meta, TPartitionId partition_id, TTransactionId transaction_id,
212
            TTabletId tablet_id, TabletUid tablet_uid, const Version& version,
213
            TabletPublishStatistics* stats, std::shared_ptr<TabletTxnInfo>& extend_tablet_txn_info,
214
            const int64_t commit_tso = -1,
215
            std::shared_ptr<const PChangelogWriteColumnMappings> column_mappings = nullptr);
216
217
    // only abort not committed txn
218
    void abort_txn(TPartitionId partition_id, TTransactionId transaction_id, TTabletId tablet_id,
219
                   TabletUid tablet_uid);
220
221
    // delete the txn from manager if it is not committed(not have a valid rowset)
222
    Status rollback_txn(TPartitionId partition_id, TTransactionId transaction_id,
223
                        TTabletId tablet_id, TabletUid tablet_uid);
224
225
    // remove the txn from txn manager
226
    // delete the related rowset if it is not null
227
    // delete rowset related data if it is not null
228
    Status delete_txn(OlapMeta* meta, TPartitionId partition_id, TTransactionId transaction_id,
229
                      TTabletId tablet_id, TabletUid tablet_uid);
230
231
    // Includes transactions keyed by this tablet and base-tablet transactions that attach this
232
    // tablet as their independent changelog tablet.
233
    void get_tablet_related_txns(TTabletId tablet_id, TabletUid tablet_uid, int64_t* partition_id,
234
                                 std::set<int64_t>* transaction_ids);
235
236
    void get_txn_related_tablets(
237
            const TTransactionId transaction_id, TPartitionId partition_ids,
238
            std::map<TabletInfo, RowsetSharedPtr>* tablet_infos,
239
            std::map<TabletInfo, std::shared_ptr<TabletTxnInfo>>* tablet_txn_infos = nullptr);
240
241
    void get_all_related_tablets(std::set<TabletInfo>* tablet_infos);
242
243
    // Get all expired txns and save them in expire_txn_map.
244
    // This is currently called before reporting all tablet info, to avoid iterating txn map for every tablets.
245
    void build_expire_txn_map(std::map<TabletInfo, std::vector<int64_t>>* expire_txn_map);
246
247
    void force_rollback_tablet_related_txns(OlapMeta* meta, TTabletId tablet_id,
248
                                            TabletUid tablet_uid);
249
250
    void get_partition_ids(const TTransactionId transaction_id,
251
                           std::vector<TPartitionId>* partition_ids);
252
253
    void set_txn_related_delete_bitmap(TPartitionId partition_id, TTransactionId transaction_id,
254
                                       TTabletId tablet_id, TabletUid tablet_uid,
255
                                       bool unique_key_merge_on_write,
256
                                       DeleteBitmapPtr delete_bitmap,
257
                                       const RowsetIdUnorderedSet& rowset_ids,
258
                                       std::shared_ptr<PartialUpdateInfo> partial_update_info);
259
    void get_all_commit_tablet_txn_info_by_tablet(
260
            const Tablet& tablet, CommitTabletTxnInfoVec* commit_tablet_txn_info_vec);
261
262
    int64_t get_txn_by_tablet_version(int64_t tablet_id, int64_t version);
263
    void update_tablet_version_txn(int64_t tablet_id, int64_t version, int64_t txn_id);
264
265
    TxnState get_txn_state(TPartitionId partition_id, TTransactionId transaction_id,
266
                           TTabletId tablet_id, TabletUid tablet_uid);
267
268
    void remove_txn_tablet_info(TPartitionId partition_id, TTransactionId transaction_id,
269
                                TTabletId tablet_id, TabletUid tablet_uid);
270
271
private:
272
    using TxnKey = std::pair<int64_t, int64_t>; // partition_id, transaction_id;
273
274
    // Implement TxnKey hash function to support TxnKey as a key for `unordered_map`.
275
    struct TxnKeyHash {
276
        template <typename T, typename U>
277
2.64k
        size_t operator()(const std::pair<T, U>& e) const {
278
2.64k
            return std::hash<T>()(e.first) ^ std::hash<U>()(e.second);
279
2.64k
        }
280
    };
281
282
    // Implement TxnKey equal function to support TxnKey as a key for `unordered_map`.
283
    struct TxnKeyEqual {
284
        template <class T, typename U>
285
2.32k
        bool operator()(const std::pair<T, U>& l, const std::pair<T, U>& r) const {
286
2.32k
            return l.first == r.first && l.second == r.second;
287
2.32k
        }
288
    };
289
290
    using txn_tablet_map_t =
291
            std::unordered_map<TxnKey, std::map<TabletInfo, std::shared_ptr<TabletTxnInfo>>,
292
                               TxnKeyHash, TxnKeyEqual>;
293
    using txn_partition_map_t = std::unordered_map<int64_t, std::unordered_set<int64_t>>;
294
    std::shared_mutex& _get_txn_map_lock(TTransactionId transactionId);
295
296
    txn_tablet_map_t& _get_txn_tablet_map(TTransactionId transactionId);
297
298
    txn_partition_map_t& _get_txn_partition_map(TTransactionId transactionId);
299
300
    inline std::shared_mutex& _get_txn_lock(TTransactionId transactionId);
301
302
    // Insert or remove (transaction_id, partition_id) from _txn_partition_map
303
    // get _txn_map_lock before calling.
304
    void _insert_txn_partition_map_unlocked(int64_t transaction_id, int64_t partition_id);
305
    void _clear_txn_partition_map_unlocked(int64_t transaction_id, int64_t partition_id);
306
307
    void _remove_txn_tablet_info_unlocked(TPartitionId partition_id, TTransactionId transaction_id,
308
                                          TTabletId tablet_id, TabletUid tablet_uid,
309
                                          std::lock_guard<std::shared_mutex>& txn_lock,
310
                                          std::lock_guard<std::shared_mutex>& wrlock);
311
312
    class TabletVersionCache : public LRUCachePolicy {
313
    public:
314
        TabletVersionCache(size_t capacity)
315
813
                : LRUCachePolicy(CachePolicy::CacheType::TABLET_VERSION_CACHE, capacity,
316
813
                                 LRUCacheType::NUMBER, /*sweeptime*/ -1,
317
813
                                 /*num_shards*/ 32,
318
813
                                 /*element_count_capacity*/ 0, /*enable_prune*/ false,
319
813
                                 /*is_lru_k*/ false) {}
320
    };
321
322
private:
323
    StorageEngine& _engine;
324
325
    const int32_t _txn_map_shard_size;
326
327
    const int32_t _txn_shard_size;
328
329
    // _txn_map_locks[i] protect _txn_tablet_maps[i], i=0,1,2...,and i < _txn_map_shard_size
330
    txn_tablet_map_t* _txn_tablet_maps = nullptr;
331
    // transaction_id -> corresponding partition ids
332
    // This is mainly for the clear txn task received from FE, which may only has transaction id,
333
    // so we need this map to find out which partitions are corresponding to a transaction id.
334
    // The _txn_partition_maps[i] should be constructed/deconstructed/modified alongside with '_txn_tablet_maps[i]'
335
    txn_partition_map_t* _txn_partition_maps = nullptr;
336
337
    std::shared_mutex* _txn_map_locks = nullptr;
338
339
    std::shared_mutex* _txn_mutex = nullptr;
340
341
    std::unique_ptr<TabletVersionCache> _tablet_version_cache;
342
    DISALLOW_COPY_AND_ASSIGN(TxnManager);
343
}; // TxnManager
344
345
2.05k
inline std::shared_mutex& TxnManager::_get_txn_map_lock(TTransactionId transactionId) {
346
2.05k
    return _txn_map_locks[transactionId & (_txn_map_shard_size - 1)];
347
2.05k
}
348
349
2.05k
inline TxnManager::txn_tablet_map_t& TxnManager::_get_txn_tablet_map(TTransactionId transactionId) {
350
2.05k
    return _txn_tablet_maps[transactionId & (_txn_map_shard_size - 1)];
351
2.05k
}
352
353
inline TxnManager::txn_partition_map_t& TxnManager::_get_txn_partition_map(
354
1.10k
        TTransactionId transactionId) {
355
1.10k
    return _txn_partition_maps[transactionId & (_txn_map_shard_size - 1)];
356
1.10k
}
357
358
1.22k
inline std::shared_mutex& TxnManager::_get_txn_lock(TTransactionId transactionId) {
359
1.22k
    return _txn_mutex[transactionId & (_txn_shard_size - 1)];
360
1.22k
}
361
362
} // namespace doris