Coverage Report

Created: 2026-08-07 19:43

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