Coverage Report

Created: 2026-03-16 12:03

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/storage/txn/txn_manager.cpp
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
#include "storage/txn/txn_manager.h"
19
20
#include <bvar/bvar.h>
21
#include <fmt/format.h>
22
#include <fmt/ranges.h>
23
#include <thrift/protocol/TDebugProtocol.h>
24
#include <time.h>
25
26
#include <filesystem>
27
#include <iterator>
28
#include <list>
29
#include <new>
30
#include <ostream>
31
#include <queue>
32
#include <set>
33
#include <string>
34
35
#include "common/config.h"
36
#include "common/logging.h"
37
#include "common/status.h"
38
#include "load/delta_writer/delta_writer.h"
39
#include "storage/data_dir.h"
40
#include "storage/olap_common.h"
41
#include "storage/partial_update_info.h"
42
#include "storage/rowset/beta_rowset.h"
43
#include "storage/rowset/pending_rowset_helper.h"
44
#include "storage/rowset/rowset_meta.h"
45
#include "storage/rowset/rowset_meta_manager.h"
46
#include "storage/schema_change/schema_change.h"
47
#include "storage/segment/segment_loader.h"
48
#include "storage/storage_engine.h"
49
#include "storage/tablet/tablet_manager.h"
50
#include "storage/tablet/tablet_meta.h"
51
#include "storage/tablet/tablet_meta_manager.h"
52
#include "storage/task/engine_publish_version_task.h"
53
#include "util/debug_points.h"
54
#include "util/time.h"
55
56
namespace doris {
57
class OlapMeta;
58
} // namespace doris
59
60
using std::map;
61
using std::pair;
62
using std::set;
63
using std::string;
64
using std::stringstream;
65
using std::vector;
66
67
namespace doris {
68
using namespace ErrorCode;
69
70
bvar::Adder<int64_t> g_tablet_txn_info_txn_partitions_count("tablet_txn_info_txn_partitions_count");
71
72
TxnManager::TxnManager(StorageEngine& engine, int32_t txn_map_shard_size, int32_t txn_shard_size)
73
345
        : _engine(engine),
74
345
          _txn_map_shard_size(txn_map_shard_size),
75
345
          _txn_shard_size(txn_shard_size) {
76
345
    DCHECK_GT(_txn_map_shard_size, 0);
77
345
    DCHECK_GT(_txn_shard_size, 0);
78
345
    DCHECK_EQ(_txn_map_shard_size & (_txn_map_shard_size - 1), 0);
79
345
    DCHECK_EQ(_txn_shard_size & (_txn_shard_size - 1), 0);
80
345
    _txn_map_locks = new std::shared_mutex[_txn_map_shard_size];
81
345
    _txn_tablet_maps = new txn_tablet_map_t[_txn_map_shard_size];
82
345
    _txn_partition_maps = new txn_partition_map_t[_txn_map_shard_size];
83
345
    _txn_mutex = new std::shared_mutex[_txn_shard_size];
84
345
    _txn_tablet_delta_writer_map = new txn_tablet_delta_writer_map_t[_txn_map_shard_size];
85
345
    _txn_tablet_delta_writer_map_locks = new std::shared_mutex[_txn_map_shard_size];
86
    // For debugging
87
345
    _tablet_version_cache = std::make_unique<TabletVersionCache>(100000);
88
345
}
89
90
// prepare txn should always be allowed because ingest task will be retried
91
// could not distinguish rollup, schema change or base table, prepare txn successfully will allow
92
// ingest retried
93
Status TxnManager::prepare_txn(TPartitionId partition_id, const Tablet& tablet,
94
                               TTransactionId transaction_id, const PUniqueId& load_id,
95
0
                               bool ingest) {
96
    // check if the tablet has already been shutdown. If it has, it indicates that
97
    // it is an old tablet, and data should not be imported into the old tablet.
98
    // Otherwise, it may lead to data loss during migration.
99
0
    if (tablet.tablet_state() == TABLET_SHUTDOWN) {
100
0
        return Status::InternalError<false>(
101
0
                "The tablet's state is shutdown, tablet_id: {}. The tablet may have been dropped "
102
0
                "or migrationed. Please check if the table has been dropped or try again.",
103
0
                tablet.tablet_id());
104
0
    }
105
0
    return prepare_txn(partition_id, transaction_id, tablet.tablet_id(), tablet.tablet_uid(),
106
0
                       load_id, ingest);
107
0
}
108
109
// most used for ut
110
Status TxnManager::prepare_txn(TPartitionId partition_id, TTransactionId transaction_id,
111
                               TTabletId tablet_id, TabletUid tablet_uid, const PUniqueId& load_id,
112
14.5k
                               bool ingest) {
113
14.5k
    TxnKey key(partition_id, transaction_id);
114
14.5k
    TabletInfo tablet_info(tablet_id, tablet_uid);
115
14.5k
    std::lock_guard<std::shared_mutex> txn_wrlock(_get_txn_map_lock(transaction_id));
116
14.5k
    txn_tablet_map_t& txn_tablet_map = _get_txn_tablet_map(transaction_id);
117
118
14.5k
    DBUG_EXECUTE_IF("TxnManager.prepare_txn.random_failed", {
119
14.5k
        if (rand() % 100 < (100 * dp->param("percent", 0.5))) {
120
14.5k
            LOG_WARNING("TxnManager.prepare_txn.random_failed random failed")
121
14.5k
                    .tag("txn_id", transaction_id)
122
14.5k
                    .tag("tablet_id", tablet_id);
123
14.5k
            return Status::InternalError("debug prepare txn random failed");
124
14.5k
        }
125
14.5k
    });
126
14.5k
    DBUG_EXECUTE_IF("TxnManager.prepare_txn.wait", {
127
14.5k
        if (auto wait = dp->param<int>("duration", 0); wait > 0) {
128
14.5k
            LOG_WARNING("TxnManager.prepare_txn.wait")
129
14.5k
                    .tag("txn_id", transaction_id)
130
14.5k
                    .tag("tablet_id", tablet_id)
131
14.5k
                    .tag("wait ms", wait);
132
14.5k
            std::this_thread::sleep_for(std::chrono::milliseconds(wait));
133
14.5k
        }
134
14.5k
    });
135
136
    /// Step 1: check if the transaction is already exist
137
14.5k
    do {
138
14.5k
        auto iter = txn_tablet_map.find(key);
139
14.5k
        if (iter == txn_tablet_map.end()) {
140
2.33k
            break;
141
2.33k
        }
142
143
        // exist TxnKey
144
12.1k
        auto& txn_tablet_info_map = iter->second;
145
12.1k
        auto load_itr = txn_tablet_info_map.find(tablet_info);
146
12.1k
        if (load_itr == txn_tablet_info_map.end()) {
147
12.1k
            break;
148
12.1k
        }
149
150
        // found load for txn,tablet
151
2
        auto& load_info = load_itr->second;
152
        // case 1: user commit rowset, then the load id must be equal
153
        // check if load id is equal
154
2
        if (load_info->load_id.hi() == load_id.hi() && load_info->load_id.lo() == load_id.lo() &&
155
2
            load_info->rowset != nullptr) {
156
1
            LOG(WARNING) << "find transaction exists when add to engine."
157
1
                         << "partition_id: " << key.first << ", transaction_id: " << key.second
158
1
                         << ", tablet: " << tablet_info.to_string();
159
1
            return Status::OK();
160
1
        }
161
2
    } while (false);
162
163
    /// Step 2: check if there are too many transactions on running.
164
    // check if there are too many transactions on running.
165
    // if yes, reject the request.
166
14.5k
    txn_partition_map_t& txn_partition_map = _get_txn_partition_map(transaction_id);
167
14.5k
    if (txn_partition_map.size() > config::max_runnings_transactions_per_txn_map) {
168
0
        return Status::Error<TOO_MANY_TRANSACTIONS>("too many transactions: {}, limit: {}",
169
0
                                                    txn_tablet_map.size(),
170
0
                                                    config::max_runnings_transactions_per_txn_map);
171
0
    }
172
173
    /// Step 3: Add transaction to engine
174
    // not found load id
175
    // case 1: user start a new txn, rowset = null
176
    // case 2: loading txn from meta env
177
14.5k
    auto load_info = std::make_shared<TabletTxnInfo>(load_id, nullptr, ingest);
178
14.5k
    load_info->prepare();
179
14.5k
    if (!txn_tablet_map.contains(key)) {
180
2.33k
        g_tablet_txn_info_txn_partitions_count << 1;
181
2.33k
    }
182
14.5k
    txn_tablet_map[key][tablet_info] = std::move(load_info);
183
14.5k
    _insert_txn_partition_map_unlocked(transaction_id, partition_id);
184
14.5k
    VLOG_NOTICE << "add transaction to engine successfully."
185
11
                << "partition_id: " << key.first << ", transaction_id: " << key.second
186
11
                << ", tablet: " << tablet_info.to_string();
187
14.5k
    return Status::OK();
188
14.5k
}
189
190
Status TxnManager::commit_txn(TPartitionId partition_id, const Tablet& tablet,
191
                              TTransactionId transaction_id, const PUniqueId& load_id,
192
                              const RowsetSharedPtr& rowset_ptr, PendingRowsetGuard guard,
193
                              bool is_recovery,
194
14.4k
                              std::shared_ptr<PartialUpdateInfo> partial_update_info) {
195
14.4k
    return commit_txn(tablet.data_dir()->get_meta(), partition_id, transaction_id,
196
14.4k
                      tablet.tablet_id(), tablet.tablet_uid(), load_id, rowset_ptr,
197
14.4k
                      std::move(guard), is_recovery, partial_update_info);
198
14.4k
}
199
200
Status TxnManager::publish_txn(TPartitionId partition_id, const TabletSharedPtr& tablet,
201
                               TTransactionId transaction_id, const Version& version,
202
                               TabletPublishStatistics* stats,
203
14.1k
                               std::shared_ptr<TabletTxnInfo>& extend_tablet_txn_info) {
204
14.1k
    return publish_txn(tablet->data_dir()->get_meta(), partition_id, transaction_id,
205
14.1k
                       tablet->tablet_id(), tablet->tablet_uid(), version, stats,
206
14.1k
                       extend_tablet_txn_info);
207
14.1k
}
208
209
void TxnManager::abort_txn(TPartitionId partition_id, TTransactionId transaction_id,
210
0
                           TTabletId tablet_id, TabletUid tablet_uid) {
211
0
    pair<int64_t, int64_t> key(partition_id, transaction_id);
212
0
    TabletInfo tablet_info(tablet_id, tablet_uid);
213
214
0
    std::shared_lock txn_rdlock(_get_txn_map_lock(transaction_id));
215
216
0
    auto& txn_tablet_map = _get_txn_tablet_map(transaction_id);
217
0
    auto it = txn_tablet_map.find(key);
218
0
    if (it == txn_tablet_map.end()) {
219
0
        return;
220
0
    }
221
222
0
    auto& tablet_txn_info_map = it->second;
223
0
    auto tablet_txn_info_iter = tablet_txn_info_map.find(tablet_info);
224
0
    if (tablet_txn_info_iter == tablet_txn_info_map.end()) {
225
0
        return;
226
0
    }
227
228
0
    auto& txn_info = tablet_txn_info_iter->second;
229
0
    txn_info->abort();
230
0
}
231
232
// delete the txn from manager if it is not committed(not have a valid rowset)
233
Status TxnManager::rollback_txn(TPartitionId partition_id, const Tablet& tablet,
234
5
                                TTransactionId transaction_id) {
235
5
    return rollback_txn(partition_id, transaction_id, tablet.tablet_id(), tablet.tablet_uid());
236
5
}
237
238
Status TxnManager::delete_txn(TPartitionId partition_id, const TabletSharedPtr& tablet,
239
272
                              TTransactionId transaction_id) {
240
272
    return delete_txn(tablet->data_dir()->get_meta(), partition_id, transaction_id,
241
272
                      tablet->tablet_id(), tablet->tablet_uid());
242
272
}
243
244
void TxnManager::set_txn_related_delete_bitmap(
245
        TPartitionId partition_id, TTransactionId transaction_id, TTabletId tablet_id,
246
        TabletUid tablet_uid, bool unique_key_merge_on_write, DeleteBitmapPtr delete_bitmap,
247
        const RowsetIdUnorderedSet& rowset_ids,
248
5.14k
        std::shared_ptr<PartialUpdateInfo> partial_update_info) {
249
5.14k
    pair<int64_t, int64_t> key(partition_id, transaction_id);
250
5.14k
    TabletInfo tablet_info(tablet_id, tablet_uid);
251
252
5.14k
    std::lock_guard<std::shared_mutex> txn_lock(_get_txn_lock(transaction_id));
253
5.14k
    {
254
        // get tx
255
5.14k
        std::lock_guard<std::shared_mutex> wrlock(_get_txn_map_lock(transaction_id));
256
5.14k
        txn_tablet_map_t& txn_tablet_map = _get_txn_tablet_map(transaction_id);
257
5.14k
        auto it = txn_tablet_map.find(key);
258
5.14k
        if (it == txn_tablet_map.end()) {
259
1
            LOG(WARNING) << "transaction_id: " << transaction_id
260
1
                         << " partition_id: " << partition_id << " may be cleared";
261
1
            return;
262
1
        }
263
5.14k
        auto load_itr = it->second.find(tablet_info);
264
5.14k
        if (load_itr == it->second.end()) {
265
0
            LOG(WARNING) << "transaction_id: " << transaction_id
266
0
                         << " partition_id: " << partition_id << " tablet_id: " << tablet_id
267
0
                         << " may be cleared";
268
0
            return;
269
0
        }
270
5.14k
        auto& load_info = load_itr->second;
271
5.14k
        load_info->unique_key_merge_on_write = unique_key_merge_on_write;
272
5.14k
        load_info->delete_bitmap = delete_bitmap;
273
5.14k
        load_info->rowset_ids = rowset_ids;
274
5.14k
        load_info->partial_update_info = partial_update_info;
275
5.14k
    }
276
5.14k
}
277
278
Status TxnManager::commit_txn(OlapMeta* meta, TPartitionId partition_id,
279
                              TTransactionId transaction_id, TTabletId tablet_id,
280
                              TabletUid tablet_uid, const PUniqueId& load_id,
281
                              const RowsetSharedPtr& rowset_ptr, PendingRowsetGuard guard,
282
                              bool is_recovery,
283
14.5k
                              std::shared_ptr<PartialUpdateInfo> partial_update_info) {
284
14.5k
    if (partition_id < 1 || transaction_id < 1 || tablet_id < 1) {
285
0
        LOG(WARNING) << "invalid commit req "
286
0
                     << " partition_id=" << partition_id << " transaction_id=" << transaction_id
287
0
                     << " tablet_id=" << tablet_id;
288
0
        return Status::InternalError("invalid partition id");
289
0
    }
290
291
14.5k
    pair<int64_t, int64_t> key(partition_id, transaction_id);
292
14.5k
    TabletInfo tablet_info(tablet_id, tablet_uid);
293
14.5k
    if (rowset_ptr == nullptr) {
294
0
        return Status::Error<ROWSET_INVALID>(
295
0
                "could not commit txn because rowset ptr is null. partition_id: {}, "
296
0
                "transaction_id: {}, tablet: {}",
297
0
                key.first, key.second, tablet_info.to_string());
298
0
    }
299
300
14.5k
    DBUG_EXECUTE_IF("TxnManager.commit_txn.random_failed", {
301
14.5k
        if (rand() % 100 < (100 * dp->param("percent", 0.5))) {
302
14.5k
            LOG_WARNING("TxnManager.commit_txn.random_failed")
303
14.5k
                    .tag("txn_id", transaction_id)
304
14.5k
                    .tag("tablet_id", tablet_id);
305
14.5k
            return Status::InternalError("debug commit txn random failed");
306
14.5k
        }
307
14.5k
    });
308
14.5k
    DBUG_EXECUTE_IF("TxnManager.commit_txn.wait", {
309
14.5k
        if (auto wait = dp->param<int>("duration", 0); wait > 0) {
310
14.5k
            LOG_WARNING("TxnManager.commit_txn.wait")
311
14.5k
                    .tag("txn_id", transaction_id)
312
14.5k
                    .tag("tablet_id", tablet_id)
313
14.5k
                    .tag("wait ms", wait);
314
14.5k
            std::this_thread::sleep_for(std::chrono::milliseconds(wait));
315
14.5k
        }
316
14.5k
    });
317
318
14.5k
    std::lock_guard<std::shared_mutex> txn_lock(_get_txn_lock(transaction_id));
319
    // this while loop just run only once, just for if break
320
14.5k
    do {
321
        // get tx
322
14.5k
        std::shared_lock rdlock(_get_txn_map_lock(transaction_id));
323
14.5k
        auto rs_pb = rowset_ptr->rowset_meta()->get_rowset_pb();
324
        // TODO(dx): remove log after fix partition id eq 0 bug
325
14.5k
        if (!rs_pb.has_partition_id() || rs_pb.partition_id() == 0) {
326
1
            rowset_ptr->rowset_meta()->set_partition_id(partition_id);
327
1
            LOG(WARNING) << "cant get partition id from rs pb, get from func arg partition_id="
328
1
                         << partition_id;
329
1
        }
330
14.5k
        txn_tablet_map_t& txn_tablet_map = _get_txn_tablet_map(transaction_id);
331
14.5k
        auto it = txn_tablet_map.find(key);
332
14.5k
        if (it == txn_tablet_map.end()) {
333
21
            break;
334
21
        }
335
336
14.5k
        auto load_itr = it->second.find(tablet_info);
337
14.5k
        if (load_itr == it->second.end()) {
338
74
            break;
339
74
        }
340
341
        // found load for txn,tablet
342
        // case 1: user commit rowset, then the load id must be equal
343
14.4k
        auto& load_info = load_itr->second;
344
        // check if load id is equal
345
14.4k
        if (load_info->rowset == nullptr) {
346
14.4k
            break;
347
14.4k
        }
348
349
2
        if (load_info->load_id.hi() != load_id.hi() || load_info->load_id.lo() != load_id.lo()) {
350
0
            break;
351
0
        }
352
353
        // find a rowset with same rowset id, then it means a duplicate call
354
2
        if (load_info->rowset->rowset_id() == rowset_ptr->rowset_id()) {
355
1
            LOG(INFO) << "find rowset exists when commit transaction to engine."
356
1
                      << "partition_id: " << key.first << ", transaction_id: " << key.second
357
1
                      << ", tablet: " << tablet_info.to_string()
358
1
                      << ", rowset_id: " << load_info->rowset->rowset_id();
359
            // Should not remove this rowset from pending rowsets
360
1
            load_info->pending_rs_guard = std::move(guard);
361
1
            return Status::OK();
362
1
        }
363
364
        // find a rowset with different rowset id, then it should not happen, just return errors
365
1
        return Status::Error<PUSH_TRANSACTION_ALREADY_EXIST>(
366
1
                "find rowset exists when commit transaction to engine. but rowset ids are not "
367
1
                "same. partition_id: {}, transaction_id: {}, tablet: {}, exist rowset_id: {}, new "
368
1
                "rowset_id: {}",
369
1
                key.first, key.second, tablet_info.to_string(),
370
1
                load_info->rowset->rowset_id().to_string(), rowset_ptr->rowset_id().to_string());
371
2
    } while (false);
372
373
    // if not in recovery mode, then should persist the meta to meta env
374
    // save meta need access disk, it maybe very slow, so that it is not in global txn lock
375
    // it is under a single txn lock
376
14.5k
    if (!is_recovery) {
377
14.5k
        Status save_status =
378
14.5k
                RowsetMetaManager::save(meta, tablet_uid, rowset_ptr->rowset_id(),
379
14.5k
                                        rowset_ptr->rowset_meta()->get_rowset_pb(), false);
380
14.5k
        DBUG_EXECUTE_IF("TxnManager.RowsetMetaManager.save_wait", {
381
14.5k
            if (auto wait = dp->param<int>("duration", 0); wait > 0) {
382
14.5k
                LOG_WARNING("TxnManager.RowsetMetaManager.save_wait")
383
14.5k
                        .tag("txn_id", transaction_id)
384
14.5k
                        .tag("tablet_id", tablet_id)
385
14.5k
                        .tag("wait ms", wait);
386
14.5k
                std::this_thread::sleep_for(std::chrono::milliseconds(wait));
387
14.5k
            }
388
14.5k
        });
389
14.5k
        if (!save_status.ok()) {
390
0
            save_status.append(fmt::format(", txn id: {}", transaction_id));
391
0
            return save_status;
392
0
        }
393
394
14.5k
        if (partial_update_info && partial_update_info->is_partial_update()) {
395
232
            PartialUpdateInfoPB partial_update_info_pb;
396
232
            partial_update_info->to_pb(&partial_update_info_pb);
397
232
            save_status = RowsetMetaManager::save_partial_update_info(
398
232
                    meta, tablet_id, partition_id, transaction_id, partial_update_info_pb);
399
232
            if (!save_status.ok()) {
400
0
                save_status.append(fmt::format(", txn_id: {}", transaction_id));
401
0
                return save_status;
402
0
            }
403
232
        }
404
14.5k
    }
405
406
14.5k
    TabletSharedPtr tablet;
407
14.5k
    std::shared_ptr<PartialUpdateInfo> decoded_partial_update_info {nullptr};
408
14.5k
    if (is_recovery) {
409
86
        tablet = _engine.tablet_manager()->get_tablet(tablet_id, tablet_uid);
410
86
        if (tablet != nullptr && tablet->enable_unique_key_merge_on_write()) {
411
0
            PartialUpdateInfoPB partial_update_info_pb;
412
0
            auto st = RowsetMetaManager::try_get_partial_update_info(
413
0
                    meta, tablet_id, partition_id, transaction_id, &partial_update_info_pb);
414
0
            if (st.ok()) {
415
0
                decoded_partial_update_info = std::make_shared<PartialUpdateInfo>();
416
0
                decoded_partial_update_info->from_pb(&partial_update_info_pb);
417
0
                DCHECK(decoded_partial_update_info->is_partial_update());
418
0
            } else if (!st.is<META_KEY_NOT_FOUND>()) {
419
                // the load is not a partial update
420
0
                return st;
421
0
            }
422
0
        }
423
86
    }
424
425
14.5k
    {
426
14.5k
        std::lock_guard<std::shared_mutex> wrlock(_get_txn_map_lock(transaction_id));
427
14.5k
        auto load_info = std::make_shared<TabletTxnInfo>(load_id, rowset_ptr);
428
14.5k
        load_info->pending_rs_guard = std::move(guard);
429
14.5k
        if (is_recovery) {
430
86
            if (tablet != nullptr && tablet->enable_unique_key_merge_on_write()) {
431
0
                load_info->unique_key_merge_on_write = true;
432
0
                load_info->delete_bitmap.reset(new DeleteBitmap(tablet->tablet_id()));
433
0
                if (decoded_partial_update_info) {
434
0
                    LOG_INFO(
435
0
                            "get partial update info from RocksDB during recovery. txn_id={}, "
436
0
                            "partition_id={}, tablet_id={}, partial_update_info=[{}]",
437
0
                            transaction_id, partition_id, tablet_id,
438
0
                            decoded_partial_update_info->summary());
439
0
                    load_info->partial_update_info = decoded_partial_update_info;
440
0
                }
441
0
            }
442
86
        }
443
14.5k
        load_info->commit();
444
445
14.5k
        txn_tablet_map_t& txn_tablet_map = _get_txn_tablet_map(transaction_id);
446
14.5k
        txn_tablet_map[key][tablet_info] = std::move(load_info);
447
14.5k
        _insert_txn_partition_map_unlocked(transaction_id, partition_id);
448
14.5k
        VLOG_NOTICE << "commit transaction to engine successfully."
449
14
                    << " partition_id: " << key.first << ", transaction_id: " << key.second
450
14
                    << ", tablet: " << tablet_info.to_string()
451
14
                    << ", rowsetid: " << rowset_ptr->rowset_id()
452
14
                    << ", version: " << rowset_ptr->version().first;
453
14.5k
    }
454
14.5k
    return Status::OK();
455
14.5k
}
456
457
// remove a txn from txn manager
458
Status TxnManager::publish_txn(OlapMeta* meta, TPartitionId partition_id,
459
                               TTransactionId transaction_id, TTabletId tablet_id,
460
                               TabletUid tablet_uid, const Version& version,
461
                               TabletPublishStatistics* stats,
462
14.1k
                               std::shared_ptr<TabletTxnInfo>& extend_tablet_txn_info) {
463
14.1k
    auto tablet = _engine.tablet_manager()->get_tablet(tablet_id);
464
14.1k
    if (tablet == nullptr) {
465
0
        return Status::OK();
466
0
    }
467
14.1k
    DCHECK(stats != nullptr);
468
469
14.1k
    pair<int64_t, int64_t> key(partition_id, transaction_id);
470
14.1k
    TabletInfo tablet_info(tablet_id, tablet_uid);
471
14.1k
    RowsetSharedPtr rowset;
472
14.1k
    std::shared_ptr<TabletTxnInfo> tablet_txn_info;
473
14.1k
    int64_t t1 = MonotonicMicros();
474
    /// Step 1: get rowset, tablet_txn_info by key
475
14.1k
    {
476
14.1k
        std::shared_lock txn_rlock(_get_txn_lock(transaction_id));
477
14.1k
        std::shared_lock txn_map_rlock(_get_txn_map_lock(transaction_id));
478
14.1k
        stats->lock_wait_time_us += MonotonicMicros() - t1;
479
480
14.1k
        txn_tablet_map_t& txn_tablet_map = _get_txn_tablet_map(transaction_id);
481
14.1k
        if (auto it = txn_tablet_map.find(key); it != txn_tablet_map.end()) {
482
14.1k
            auto& tablet_map = it->second;
483
14.1k
            if (auto txn_info_iter = tablet_map.find(tablet_info);
484
14.1k
                txn_info_iter != tablet_map.end()) {
485
                // found load for txn,tablet
486
                // case 1: user commit rowset, then the load id must be equal
487
14.1k
                tablet_txn_info = txn_info_iter->second;
488
14.1k
                extend_tablet_txn_info = tablet_txn_info;
489
14.1k
                rowset = tablet_txn_info->rowset;
490
14.1k
            }
491
14.1k
        }
492
14.1k
    }
493
14.1k
    if (rowset == nullptr) {
494
1
        return Status::Error<TRANSACTION_NOT_EXIST>(
495
1
                "publish txn failed, rowset not found. partition_id={}, transaction_id={}, "
496
1
                "tablet={}",
497
1
                partition_id, transaction_id, tablet_info.to_string());
498
1
    }
499
14.1k
    DBUG_EXECUTE_IF("TxnManager.publish_txn.random_failed_before_save_rs_meta", {
500
14.1k
        if (rand() % 100 < (100 * dp->param("percent", 0.5))) {
501
14.1k
            LOG_WARNING("TxnManager.publish_txn.random_failed_before_save_rs_meta")
502
14.1k
                    .tag("txn_id", transaction_id)
503
14.1k
                    .tag("tablet_id", tablet_id);
504
14.1k
            return Status::InternalError("debug publish txn before save rs meta random failed");
505
14.1k
        }
506
14.1k
    });
507
14.1k
    DBUG_EXECUTE_IF("TxnManager.publish_txn.wait_before_save_rs_meta", {
508
14.1k
        if (auto wait = dp->param<int>("duration", 0); wait > 0) {
509
14.1k
            LOG_WARNING("TxnManager.publish_txn.wait_before_save_rs_meta")
510
14.1k
                    .tag("txn_id", transaction_id)
511
14.1k
                    .tag("tablet_id", tablet_id)
512
14.1k
                    .tag("wait ms", wait);
513
14.1k
            std::this_thread::sleep_for(std::chrono::milliseconds(wait));
514
14.1k
        }
515
14.1k
    });
516
517
    /// Step 2: make rowset visible
518
    // save meta need access disk, it maybe very slow, so that it is not in global txn lock
519
    // it is under a single txn lock
520
    // TODO(ygl): rowset is already set version here, memory is changed, if save failed
521
    // it maybe a fatal error
522
14.1k
    rowset->make_visible(version);
523
524
14.1k
    DBUG_EXECUTE_IF("TxnManager.publish_txn.random_failed_after_save_rs_meta", {
525
14.1k
        if (rand() % 100 < (100 * dp->param("percent", 0.5))) {
526
14.1k
            LOG_WARNING("TxnManager.publish_txn.random_failed_after_save_rs_meta")
527
14.1k
                    .tag("txn_id", transaction_id)
528
14.1k
                    .tag("tablet_id", tablet_id);
529
14.1k
            return Status::InternalError("debug publish txn after save rs meta random failed");
530
14.1k
        }
531
14.1k
    });
532
14.1k
    DBUG_EXECUTE_IF("TxnManager.publish_txn.wait_after_save_rs_meta", {
533
14.1k
        if (auto wait = dp->param<int>("duration", 0); wait > 0) {
534
14.1k
            LOG_WARNING("TxnManager.publish_txn.wait_after_save_rs_meta")
535
14.1k
                    .tag("txn_id", transaction_id)
536
14.1k
                    .tag("tablet_id", tablet_id)
537
14.1k
                    .tag("wait ms", wait);
538
14.1k
            std::this_thread::sleep_for(std::chrono::milliseconds(wait));
539
14.1k
        }
540
14.1k
    });
541
    // update delete_bitmap
542
14.1k
    if (tablet_txn_info->unique_key_merge_on_write) {
543
5.04k
        int64_t t2 = MonotonicMicros();
544
5.04k
        if (rowset->num_segments() > 1 &&
545
5.04k
            !tablet_txn_info->delete_bitmap->has_calculated_for_multi_segments(
546
0
                    rowset->rowset_id())) {
547
            // delete bitmap is empty, should re-calculate delete bitmaps between segments
548
0
            std::vector<segment_v2::SegmentSharedPtr> segments;
549
0
            RETURN_IF_ERROR(std::static_pointer_cast<BetaRowset>(rowset)->load_segments(&segments));
550
0
            RETURN_IF_ERROR(tablet->calc_delete_bitmap_between_segments(
551
0
                    rowset->tablet_schema(), rowset->rowset_id(), segments,
552
0
                    tablet_txn_info->delete_bitmap));
553
0
        }
554
555
5.04k
        RETURN_IF_ERROR(
556
5.04k
                Tablet::update_delete_bitmap(tablet, tablet_txn_info.get(), transaction_id));
557
5.04k
        int64_t t3 = MonotonicMicros();
558
5.04k
        stats->calc_delete_bitmap_time_us = t3 - t2;
559
5.04k
        RETURN_IF_ERROR(TabletMetaManager::save_delete_bitmap(
560
5.04k
                tablet->data_dir(), tablet->tablet_id(), tablet_txn_info->delete_bitmap,
561
5.04k
                version.second));
562
5.04k
        stats->save_meta_time_us = MonotonicMicros() - t3;
563
5.04k
    }
564
565
    /// Step 3:  add to binlog
566
14.1k
    auto enable_binlog = tablet->is_enable_binlog();
567
14.1k
    if (enable_binlog) {
568
0
        auto status = rowset->add_to_binlog();
569
0
        if (!status.ok()) {
570
0
            return Status::Error<ROWSET_ADD_TO_BINLOG_FAILED>(
571
0
                    "add rowset to binlog failed. when publish txn rowset_id: {}, tablet id: {}, "
572
0
                    "txn id: {}, status: {}",
573
0
                    rowset->rowset_id().to_string(), tablet_id, transaction_id,
574
0
                    status.to_string_no_stack());
575
0
        }
576
0
    }
577
578
    /// Step 4: save meta
579
14.1k
    int64_t t5 = MonotonicMicros();
580
14.1k
    auto status = RowsetMetaManager::save(meta, tablet_uid, rowset->rowset_id(),
581
14.1k
                                          rowset->rowset_meta()->get_rowset_pb(), enable_binlog);
582
14.1k
    stats->save_meta_time_us += MonotonicMicros() - t5;
583
14.1k
    if (!status.ok()) {
584
0
        status.append(fmt::format(", txn id: {}", transaction_id));
585
0
        return status;
586
0
    }
587
588
14.1k
    if (tablet_txn_info->unique_key_merge_on_write && tablet_txn_info->partial_update_info &&
589
14.1k
        tablet_txn_info->partial_update_info->is_partial_update()) {
590
230
        status = RowsetMetaManager::remove_partial_update_info(meta, tablet_id, partition_id,
591
230
                                                               transaction_id);
592
230
        if (!status) {
593
            // discard the error status and print the warning log
594
0
            LOG_WARNING(
595
0
                    "fail to remove partial update info from RocksDB. txn_id={}, rowset_id={}, "
596
0
                    "tablet_id={}, tablet_uid={}",
597
0
                    transaction_id, rowset->rowset_id().to_string(), tablet_id,
598
0
                    tablet_uid.to_string());
599
0
        }
600
230
    }
601
602
    // TODO(Drogon): remove these test codes
603
14.1k
    if (enable_binlog) {
604
0
        auto version_str = fmt::format("{}", version.first);
605
0
        VLOG_DEBUG << fmt::format("tabletid: {}, version: {}, binlog filepath: {}", tablet_id,
606
0
                                  version_str, tablet->get_binlog_filepath(version_str));
607
0
    }
608
609
    /// Step 5: remove tablet_info from tnx_tablet_map
610
    // txn_tablet_map[key] empty, remove key from txn_tablet_map
611
14.1k
    int64_t t6 = MonotonicMicros();
612
14.1k
    std::lock_guard<std::shared_mutex> txn_lock(_get_txn_lock(transaction_id));
613
14.1k
    std::lock_guard<std::shared_mutex> wrlock(_get_txn_map_lock(transaction_id));
614
14.1k
    stats->lock_wait_time_us += MonotonicMicros() - t6;
615
14.1k
    _remove_txn_tablet_info_unlocked(partition_id, transaction_id, tablet_id, tablet_uid, txn_lock,
616
14.1k
                                     wrlock);
617
18.4E
    VLOG_NOTICE << "publish txn successfully."
618
18.4E
                << " partition_id: " << key.first << ", txn_id: " << key.second
619
18.4E
                << ", tablet_id: " << tablet_info.tablet_id << ", rowsetid: " << rowset->rowset_id()
620
18.4E
                << ", version: " << version.first << "," << version.second;
621
14.1k
    return status;
622
14.1k
}
623
624
void TxnManager::_remove_txn_tablet_info_unlocked(TPartitionId partition_id,
625
                                                  TTransactionId transaction_id,
626
                                                  TTabletId tablet_id, TabletUid tablet_uid,
627
                                                  std::lock_guard<std::shared_mutex>& txn_lock,
628
14.1k
                                                  std::lock_guard<std::shared_mutex>& wrlock) {
629
14.1k
    std::pair<int64_t, int64_t> key {partition_id, transaction_id};
630
14.1k
    TabletInfo tablet_info {tablet_id, tablet_uid};
631
14.1k
    txn_tablet_map_t& txn_tablet_map = _get_txn_tablet_map(transaction_id);
632
14.1k
    if (auto it = txn_tablet_map.find(key); it != txn_tablet_map.end()) {
633
14.1k
        it->second.erase(tablet_info);
634
14.1k
        if (it->second.empty()) {
635
2.29k
            txn_tablet_map.erase(it);
636
2.29k
            g_tablet_txn_info_txn_partitions_count << -1;
637
2.29k
            _clear_txn_partition_map_unlocked(transaction_id, partition_id);
638
2.29k
        }
639
14.1k
    }
640
14.1k
}
641
642
void TxnManager::remove_txn_tablet_info(TPartitionId partition_id, TTransactionId transaction_id,
643
0
                                        TTabletId tablet_id, TabletUid tablet_uid) {
644
0
    std::lock_guard<std::shared_mutex> txn_lock(_get_txn_lock(transaction_id));
645
0
    std::lock_guard<std::shared_mutex> wrlock(_get_txn_map_lock(transaction_id));
646
0
    _remove_txn_tablet_info_unlocked(partition_id, transaction_id, tablet_id, tablet_uid, txn_lock,
647
0
                                     wrlock);
648
0
}
649
650
// txn could be rollbacked if it does not have related rowset
651
// if the txn has related rowset then could not rollback it, because it
652
// may be committed in another thread and our current thread meets errors when writing to data file
653
// BE has to wait for fe call clear txn api
654
Status TxnManager::rollback_txn(TPartitionId partition_id, TTransactionId transaction_id,
655
7
                                TTabletId tablet_id, TabletUid tablet_uid) {
656
7
    pair<int64_t, int64_t> key(partition_id, transaction_id);
657
7
    TabletInfo tablet_info(tablet_id, tablet_uid);
658
659
7
    std::lock_guard<std::shared_mutex> wrlock(_get_txn_map_lock(transaction_id));
660
7
    txn_tablet_map_t& txn_tablet_map = _get_txn_tablet_map(transaction_id);
661
662
7
    auto it = txn_tablet_map.find(key);
663
7
    if (it == txn_tablet_map.end()) {
664
0
        return Status::OK();
665
0
    }
666
667
7
    auto& tablet_txn_info_map = it->second;
668
7
    if (auto load_itr = tablet_txn_info_map.find(tablet_info);
669
7
        load_itr != tablet_txn_info_map.end()) {
670
        // found load for txn,tablet
671
        // case 1: user commit rowset, then the load id must be equal
672
7
        const auto& load_info = load_itr->second;
673
7
        if (load_info->rowset != nullptr) {
674
1
            return Status::Error<TRANSACTION_ALREADY_COMMITTED>(
675
1
                    "if rowset is not null, it means other thread may commit the rowset should "
676
1
                    "not delete txn any more");
677
1
        }
678
7
    }
679
680
6
    tablet_txn_info_map.erase(tablet_info);
681
6
    LOG(INFO) << "rollback transaction from engine successfully."
682
6
              << " partition_id: " << key.first << ", transaction_id: " << key.second
683
6
              << ", tablet: " << tablet_info.to_string();
684
6
    if (tablet_txn_info_map.empty()) {
685
6
        txn_tablet_map.erase(it);
686
6
        g_tablet_txn_info_txn_partitions_count << -1;
687
6
        _clear_txn_partition_map_unlocked(transaction_id, partition_id);
688
6
    }
689
6
    return Status::OK();
690
7
}
691
692
// fe call this api to clear unused rowsets in be
693
// could not delete the rowset if it already has a valid version
694
Status TxnManager::delete_txn(OlapMeta* meta, TPartitionId partition_id,
695
                              TTransactionId transaction_id, TTabletId tablet_id,
696
276
                              TabletUid tablet_uid) {
697
276
    pair<int64_t, int64_t> key(partition_id, transaction_id);
698
276
    TabletInfo tablet_info(tablet_id, tablet_uid);
699
276
    std::lock_guard<std::shared_mutex> txn_wrlock(_get_txn_map_lock(transaction_id));
700
276
    txn_tablet_map_t& txn_tablet_map = _get_txn_tablet_map(transaction_id);
701
276
    auto it = txn_tablet_map.find(key);
702
276
    if (it == txn_tablet_map.end()) {
703
0
        return Status::Error<TRANSACTION_NOT_EXIST>("key not founded from txn_tablet_map");
704
0
    }
705
276
    Status st = Status::OK();
706
276
    auto load_itr = it->second.find(tablet_info);
707
276
    if (load_itr != it->second.end()) {
708
        // found load for txn,tablet
709
        // case 1: user commit rowset, then the load id must be equal
710
276
        auto& load_info = load_itr->second;
711
276
        auto& rowset = load_info->rowset;
712
276
        if (rowset != nullptr && meta != nullptr) {
713
275
            if (!rowset->is_pending()) {
714
1
                st = Status::Error<TRANSACTION_ALREADY_COMMITTED>(
715
1
                        "could not delete transaction from engine, just remove it from memory not "
716
1
                        "delete from disk, because related rowset already published. partition_id: "
717
1
                        "{}, transaction_id: {}, tablet: {}, rowset id: {}, version: {}, state: {}",
718
1
                        key.first, key.second, tablet_info.to_string(),
719
1
                        rowset->rowset_id().to_string(), rowset->version().to_string(),
720
1
                        RowsetStatePB_Name(rowset->rowset_meta_state()));
721
274
            } else {
722
274
                static_cast<void>(RowsetMetaManager::remove(meta, tablet_uid, rowset->rowset_id()));
723
274
#ifndef BE_TEST
724
274
                _engine.add_unused_rowset(rowset);
725
274
#endif
726
274
                VLOG_NOTICE << "delete transaction from engine successfully."
727
2
                            << " partition_id: " << key.first << ", transaction_id: " << key.second
728
2
                            << ", tablet: " << tablet_info.to_string() << ", rowset: "
729
2
                            << (rowset != nullptr ? rowset->rowset_id().to_string() : "0");
730
274
            }
731
275
        }
732
276
        it->second.erase(load_itr);
733
276
    }
734
276
    if (it->second.empty()) {
735
18
        txn_tablet_map.erase(it);
736
18
        g_tablet_txn_info_txn_partitions_count << -1;
737
18
        _clear_txn_partition_map_unlocked(transaction_id, partition_id);
738
18
    }
739
276
    return st;
740
276
}
741
742
void TxnManager::get_tablet_related_txns(TTabletId tablet_id, TabletUid tablet_uid,
743
                                         int64_t* partition_id,
744
6
                                         std::set<int64_t>* transaction_ids) {
745
6
    if (partition_id == nullptr || transaction_ids == nullptr) {
746
0
        LOG(WARNING) << "parameter is null when get transactions by tablet";
747
0
        return;
748
0
    }
749
750
6
    TabletInfo tablet_info(tablet_id, tablet_uid);
751
12
    for (int32_t i = 0; i < _txn_map_shard_size; i++) {
752
6
        std::shared_lock txn_rdlock(_txn_map_locks[i]);
753
6
        txn_tablet_map_t& txn_tablet_map = _txn_tablet_maps[i];
754
6
        for (auto& it : txn_tablet_map) {
755
1
            if (it.second.find(tablet_info) != it.second.end()) {
756
1
                *partition_id = it.first.first;
757
1
                transaction_ids->insert(it.first.second);
758
1
                VLOG_NOTICE << "find transaction on tablet."
759
1
                            << "partition_id: " << it.first.first
760
1
                            << ", transaction_id: " << it.first.second
761
1
                            << ", tablet: " << tablet_info.to_string();
762
1
            }
763
1
        }
764
6
    }
765
6
}
766
767
// force drop all txns related with the tablet
768
// maybe lock error, because not get txn lock before remove from meta
769
void TxnManager::force_rollback_tablet_related_txns(OlapMeta* meta, TTabletId tablet_id,
770
3.26k
                                                    TabletUid tablet_uid) {
771
3.26k
    TabletInfo tablet_info(tablet_id, tablet_uid);
772
3.22M
    for (int32_t i = 0; i < _txn_map_shard_size; i++) {
773
3.22M
        std::lock_guard<std::shared_mutex> txn_wrlock(_txn_map_locks[i]);
774
3.22M
        txn_tablet_map_t& txn_tablet_map = _txn_tablet_maps[i];
775
3.23M
        for (auto it = txn_tablet_map.begin(); it != txn_tablet_map.end();) {
776
5.39k
            auto load_itr = it->second.find(tablet_info);
777
5.39k
            if (load_itr != it->second.end()) {
778
22
                auto& load_info = load_itr->second;
779
22
                auto& rowset = load_info->rowset;
780
22
                if (rowset != nullptr && meta != nullptr) {
781
22
                    LOG(INFO) << " delete transaction from engine "
782
22
                              << ", tablet: " << tablet_info.to_string()
783
22
                              << ", rowset id: " << rowset->rowset_id();
784
22
                    static_cast<void>(
785
22
                            RowsetMetaManager::remove(meta, tablet_uid, rowset->rowset_id()));
786
22
                }
787
22
                LOG(INFO) << "remove tablet related txn."
788
22
                          << " partition_id: " << it->first.first
789
22
                          << ", transaction_id: " << it->first.second
790
22
                          << ", tablet: " << tablet_info.to_string() << ", rowset: "
791
22
                          << (rowset != nullptr ? rowset->rowset_id().to_string() : "0");
792
22
                it->second.erase(load_itr);
793
22
            }
794
5.39k
            if (it->second.empty()) {
795
4
                _clear_txn_partition_map_unlocked(it->first.second, it->first.first);
796
4
                it = txn_tablet_map.erase(it);
797
4
                g_tablet_txn_info_txn_partitions_count << -1;
798
5.39k
            } else {
799
5.39k
                ++it;
800
5.39k
            }
801
5.39k
        }
802
3.22M
    }
803
3.26k
    if (meta != nullptr) {
804
3.26k
        Status st = RowsetMetaManager::remove_tablet_related_partial_update_info(meta, tablet_id);
805
3.26k
        if (!st.ok()) {
806
0
            LOG_WARNING("failed to partial update info, tablet_id={}, err={}", tablet_id,
807
0
                        st.to_string());
808
0
        }
809
3.26k
    }
810
3.26k
}
811
812
void TxnManager::get_txn_related_tablets(const TTransactionId transaction_id,
813
                                         TPartitionId partition_id,
814
2.44k
                                         std::map<TabletInfo, RowsetSharedPtr>* tablet_infos) {
815
    // get tablets in this transaction
816
2.44k
    pair<int64_t, int64_t> key(partition_id, transaction_id);
817
2.44k
    std::shared_lock txn_rdlock(_get_txn_map_lock(transaction_id));
818
2.44k
    txn_tablet_map_t& txn_tablet_map = _get_txn_tablet_map(transaction_id);
819
2.44k
    auto it = txn_tablet_map.find(key);
820
2.44k
    if (it == txn_tablet_map.end()) {
821
2
        VLOG_NOTICE << "could not find tablet for"
822
1
                    << " partition_id=" << partition_id << ", transaction_id=" << transaction_id;
823
2
        return;
824
2
    }
825
2.44k
    auto& load_info_map = it->second;
826
827
    // each tablet
828
14.5k
    for (auto& load_info : load_info_map) {
829
14.5k
        const TabletInfo& tablet_info = load_info.first;
830
        // must not check rowset == null here, because if rowset == null
831
        // publish version should failed
832
14.5k
        tablet_infos->emplace(tablet_info, load_info.second->rowset);
833
14.5k
    }
834
2.44k
}
835
836
54
void TxnManager::get_all_related_tablets(std::set<TabletInfo>* tablet_infos) {
837
55.3k
    for (int32_t i = 0; i < _txn_map_shard_size; i++) {
838
55.2k
        std::shared_lock txn_rdlock(_txn_map_locks[i]);
839
55.2k
        for (auto& it : _txn_tablet_maps[i]) {
840
1.01k
            for (auto& tablet_load_it : it.second) {
841
1.01k
                tablet_infos->emplace(tablet_load_it.first);
842
1.01k
            }
843
64
        }
844
55.2k
    }
845
54
}
846
847
void TxnManager::get_all_commit_tablet_txn_info_by_tablet(
848
682
        const Tablet& tablet, CommitTabletTxnInfoVec* commit_tablet_txn_info_vec) {
849
690k
    for (int32_t i = 0; i < _txn_map_shard_size; i++) {
850
690k
        std::shared_lock txn_rdlock(_txn_map_locks[i]);
851
690k
        for (const auto& [txn_key, load_info_map] : _txn_tablet_maps[i]) {
852
963
            auto tablet_load_it = load_info_map.find(tablet.get_tablet_info());
853
963
            if (tablet_load_it != load_info_map.end()) {
854
22
                const auto& [_, load_info] = *tablet_load_it;
855
22
                const auto& rowset = load_info->rowset;
856
22
                const auto& delete_bitmap = load_info->delete_bitmap;
857
22
                if (!rowset || !delete_bitmap) {
858
11
                    continue;
859
11
                }
860
11
                commit_tablet_txn_info_vec->push_back({
861
11
                        .transaction_id = txn_key.second,
862
11
                        .partition_id = txn_key.first,
863
11
                        .delete_bitmap = delete_bitmap,
864
11
                        .rowset_ids = load_info->rowset_ids,
865
11
                        .partial_update_info = load_info->partial_update_info,
866
11
                });
867
11
            }
868
963
        }
869
690k
    }
870
682
}
871
872
145
void TxnManager::build_expire_txn_map(std::map<TabletInfo, std::vector<int64_t>>* expire_txn_map) {
873
145
    int64_t now = UnixSeconds();
874
    // traverse the txn map, and get all expired txns
875
148k
    for (int32_t i = 0; i < _txn_map_shard_size; i++) {
876
148k
        std::shared_lock txn_rdlock(_txn_map_locks[i]);
877
148k
        for (auto&& [txn_key, tablet_txn_infos] : _txn_tablet_maps[i]) {
878
161
            auto txn_id = txn_key.second;
879
2.67k
            for (auto&& [tablet_info, txn_info] : tablet_txn_infos) {
880
2.67k
                double diff = difftime(now, txn_info->creation_time);
881
2.67k
                if (diff < config::pending_data_expire_time_sec) {
882
2.65k
                    continue;
883
2.65k
                }
884
885
20
                (*expire_txn_map)[tablet_info].push_back(txn_id);
886
20
                if (VLOG_IS_ON(3)) {
887
0
                    VLOG_NOTICE << "find expired txn."
888
0
                                << " tablet=" << tablet_info.to_string()
889
0
                                << " transaction_id=" << txn_id << " exist_sec=" << diff;
890
0
                }
891
20
            }
892
161
        }
893
148k
    }
894
145
}
895
896
void TxnManager::get_partition_ids(const TTransactionId transaction_id,
897
14
                                   std::vector<TPartitionId>* partition_ids) {
898
14
    std::shared_lock txn_rdlock(_get_txn_map_lock(transaction_id));
899
14
    txn_partition_map_t& txn_partition_map = _get_txn_partition_map(transaction_id);
900
14
    auto it = txn_partition_map.find(transaction_id);
901
14
    if (it != txn_partition_map.end()) {
902
13
        for (int64_t partition_id : it->second) {
903
13
            partition_ids->push_back(partition_id);
904
13
        }
905
13
    }
906
14
}
907
908
29.0k
void TxnManager::_insert_txn_partition_map_unlocked(int64_t transaction_id, int64_t partition_id) {
909
29.0k
    txn_partition_map_t& txn_partition_map = _get_txn_partition_map(transaction_id);
910
29.0k
    auto find = txn_partition_map.find(transaction_id);
911
29.0k
    if (find == txn_partition_map.end()) {
912
2.32k
        txn_partition_map[transaction_id] = std::unordered_set<int64_t>();
913
2.32k
    }
914
29.0k
    txn_partition_map[transaction_id].insert(partition_id);
915
29.0k
}
916
917
2.32k
void TxnManager::_clear_txn_partition_map_unlocked(int64_t transaction_id, int64_t partition_id) {
918
2.32k
    txn_partition_map_t& txn_partition_map = _get_txn_partition_map(transaction_id);
919
2.32k
    auto it = txn_partition_map.find(transaction_id);
920
2.32k
    if (it != txn_partition_map.end()) {
921
2.32k
        it->second.erase(partition_id);
922
2.32k
        if (it->second.empty()) {
923
2.29k
            txn_partition_map.erase(it);
924
2.29k
        }
925
2.32k
    }
926
2.32k
}
927
928
void TxnManager::add_txn_tablet_delta_writer(int64_t transaction_id, int64_t tablet_id,
929
0
                                             DeltaWriter* delta_writer) {
930
0
    std::lock_guard<std::shared_mutex> txn_wrlock(
931
0
            _get_txn_tablet_delta_writer_map_lock(transaction_id));
932
0
    txn_tablet_delta_writer_map_t& txn_tablet_delta_writer_map =
933
0
            _get_txn_tablet_delta_writer_map(transaction_id);
934
0
    auto find = txn_tablet_delta_writer_map.find(transaction_id);
935
0
    if (find == txn_tablet_delta_writer_map.end()) {
936
0
        txn_tablet_delta_writer_map[transaction_id] = std::map<int64_t, DeltaWriter*>();
937
0
    }
938
0
    txn_tablet_delta_writer_map[transaction_id][tablet_id] = delta_writer;
939
0
}
940
941
void TxnManager::finish_slave_tablet_pull_rowset(int64_t transaction_id, int64_t tablet_id,
942
0
                                                 int64_t node_id, bool is_succeed) {
943
0
    std::lock_guard<std::shared_mutex> txn_wrlock(
944
0
            _get_txn_tablet_delta_writer_map_lock(transaction_id));
945
0
    txn_tablet_delta_writer_map_t& txn_tablet_delta_writer_map =
946
0
            _get_txn_tablet_delta_writer_map(transaction_id);
947
0
    auto find_txn = txn_tablet_delta_writer_map.find(transaction_id);
948
0
    if (find_txn == txn_tablet_delta_writer_map.end()) {
949
0
        LOG(WARNING) << "delta writer manager is not exist, txn_id=" << transaction_id
950
0
                     << ", tablet_id=" << tablet_id;
951
0
        return;
952
0
    }
953
0
    auto find_tablet = txn_tablet_delta_writer_map[transaction_id].find(tablet_id);
954
0
    if (find_tablet == txn_tablet_delta_writer_map[transaction_id].end()) {
955
0
        LOG(WARNING) << "delta writer is not exist, txn_id=" << transaction_id
956
0
                     << ", tablet_id=" << tablet_id;
957
0
        return;
958
0
    }
959
0
    DeltaWriter* delta_writer = txn_tablet_delta_writer_map[transaction_id][tablet_id];
960
0
    delta_writer->finish_slave_tablet_pull_rowset(node_id, is_succeed);
961
0
}
962
963
0
void TxnManager::clear_txn_tablet_delta_writer(int64_t transaction_id) {
964
0
    std::lock_guard<std::shared_mutex> txn_wrlock(
965
0
            _get_txn_tablet_delta_writer_map_lock(transaction_id));
966
0
    txn_tablet_delta_writer_map_t& txn_tablet_delta_writer_map =
967
0
            _get_txn_tablet_delta_writer_map(transaction_id);
968
0
    auto it = txn_tablet_delta_writer_map.find(transaction_id);
969
0
    if (it != txn_tablet_delta_writer_map.end()) {
970
0
        txn_tablet_delta_writer_map.erase(it);
971
0
    }
972
0
    VLOG_CRITICAL << "remove delta writer manager, txn_id=" << transaction_id;
973
0
}
974
975
5.29k
int64_t TxnManager::get_txn_by_tablet_version(int64_t tablet_id, int64_t version) {
976
5.29k
    char key[16];
977
5.29k
    memcpy(key, &tablet_id, sizeof(int64_t));
978
5.29k
    memcpy(key + sizeof(int64_t), &version, sizeof(int64_t));
979
5.29k
    CacheKey cache_key((const char*)&key, sizeof(key));
980
981
5.29k
    auto* handle = _tablet_version_cache->lookup(cache_key);
982
5.29k
    if (handle == nullptr) {
983
5.04k
        return -1;
984
5.04k
    }
985
245
    int64_t res = ((CacheValue*)_tablet_version_cache->value(handle))->value;
986
245
    _tablet_version_cache->release(handle);
987
245
    return res;
988
5.29k
}
989
990
5.05k
void TxnManager::update_tablet_version_txn(int64_t tablet_id, int64_t version, int64_t txn_id) {
991
5.05k
    char key[16];
992
5.05k
    memcpy(key, &tablet_id, sizeof(int64_t));
993
5.05k
    memcpy(key + sizeof(int64_t), &version, sizeof(int64_t));
994
5.05k
    CacheKey cache_key((const char*)&key, sizeof(key));
995
996
5.05k
    auto* value = new CacheValue;
997
5.05k
    value->value = txn_id;
998
5.05k
    auto* handle = _tablet_version_cache->insert(cache_key, value, 1, sizeof(txn_id),
999
5.05k
                                                 CachePriority::NORMAL);
1000
5.05k
    _tablet_version_cache->release(handle);
1001
5.05k
}
1002
1003
TxnState TxnManager::get_txn_state(TPartitionId partition_id, TTransactionId transaction_id,
1004
0
                                   TTabletId tablet_id, TabletUid tablet_uid) {
1005
0
    pair<int64_t, int64_t> key(partition_id, transaction_id);
1006
0
    TabletInfo tablet_info(tablet_id, tablet_uid);
1007
1008
0
    std::shared_lock txn_rdlock(_get_txn_map_lock(transaction_id));
1009
1010
0
    auto& txn_tablet_map = _get_txn_tablet_map(transaction_id);
1011
0
    auto it = txn_tablet_map.find(key);
1012
0
    if (it == txn_tablet_map.end()) {
1013
0
        return TxnState::NOT_FOUND;
1014
0
    }
1015
1016
0
    auto& tablet_txn_info_map = it->second;
1017
0
    auto tablet_txn_info_iter = tablet_txn_info_map.find(tablet_info);
1018
0
    if (tablet_txn_info_iter == tablet_txn_info_map.end()) {
1019
0
        return TxnState::NOT_FOUND;
1020
0
    }
1021
1022
0
    const auto& txn_info = tablet_txn_info_iter->second;
1023
0
    return txn_info->state;
1024
0
}
1025
1026
} // namespace doris