Coverage Report

Created: 2026-07-30 15:36

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
485
        : _engine(engine),
76
485
          _txn_map_shard_size(txn_map_shard_size),
77
485
          _txn_shard_size(txn_shard_size) {
78
485
    DCHECK_GT(_txn_map_shard_size, 0);
79
485
    DCHECK_GT(_txn_shard_size, 0);
80
485
    DCHECK_EQ(_txn_map_shard_size & (_txn_map_shard_size - 1), 0);
81
485
    DCHECK_EQ(_txn_shard_size & (_txn_shard_size - 1), 0);
82
485
    _txn_map_locks = new std::shared_mutex[_txn_map_shard_size];
83
485
    _txn_tablet_maps = new txn_tablet_map_t[_txn_map_shard_size];
84
485
    _txn_partition_maps = new txn_partition_map_t[_txn_map_shard_size];
85
485
    _txn_mutex = new std::shared_mutex[_txn_shard_size];
86
485
    _txn_tablet_delta_writer_map = new txn_tablet_delta_writer_map_t[_txn_map_shard_size];
87
485
    _txn_tablet_delta_writer_map_locks = new std::shared_mutex[_txn_map_shard_size];
88
    // For debugging
89
485
    _tablet_version_cache = std::make_unique<TabletVersionCache>(100000);
90
485
}
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
0
                               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
0
    if (tablet.tablet_state() == TABLET_SHUTDOWN) {
102
0
        return Status::InternalError<false>(
103
0
                "The tablet's state is shutdown, tablet_id: {}. The tablet may have been dropped "
104
0
                "or migrationed. Please check if the table has been dropped or try again.",
105
0
                tablet.tablet_id());
106
0
    }
107
0
    return prepare_txn(partition_id, transaction_id, tablet.tablet_id(), tablet.tablet_uid(),
108
0
                       load_id, ingest);
109
0
}
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
47.6k
                               bool ingest) {
115
47.6k
    TxnKey key(partition_id, transaction_id);
116
47.6k
    TabletInfo tablet_info(tablet_id, tablet_uid);
117
47.6k
    std::lock_guard<std::shared_mutex> txn_wrlock(_get_txn_map_lock(transaction_id));
118
47.6k
    txn_tablet_map_t& txn_tablet_map = _get_txn_tablet_map(transaction_id);
119
120
47.6k
    DBUG_EXECUTE_IF("TxnManager.prepare_txn.random_failed", {
121
47.6k
        if (rand() % 100 < (100 * dp->param("percent", 0.5))) {
122
47.6k
            LOG_WARNING("TxnManager.prepare_txn.random_failed random failed")
123
47.6k
                    .tag("txn_id", transaction_id)
124
47.6k
                    .tag("tablet_id", tablet_id);
125
47.6k
            return Status::InternalError("debug prepare txn random failed");
126
47.6k
        }
127
47.6k
    });
128
47.6k
    DBUG_EXECUTE_IF("TxnManager.prepare_txn.wait", {
129
47.6k
        if (auto wait = dp->param<int>("duration", 0); wait > 0) {
130
47.6k
            LOG_WARNING("TxnManager.prepare_txn.wait")
131
47.6k
                    .tag("txn_id", transaction_id)
132
47.6k
                    .tag("tablet_id", tablet_id)
133
47.6k
                    .tag("wait ms", wait);
134
47.6k
            std::this_thread::sleep_for(std::chrono::milliseconds(wait));
135
47.6k
        }
136
47.6k
    });
137
138
    /// Step 1: check if the transaction is already exist
139
47.6k
    do {
140
47.6k
        auto iter = txn_tablet_map.find(key);
141
47.6k
        if (iter == txn_tablet_map.end()) {
142
6.05k
            break;
143
6.05k
        }
144
145
        // exist TxnKey
146
41.5k
        auto& txn_tablet_info_map = iter->second;
147
41.5k
        auto load_itr = txn_tablet_info_map.find(tablet_info);
148
41.5k
        if (load_itr == txn_tablet_info_map.end()) {
149
41.5k
            break;
150
41.5k
        }
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
47.6k
    txn_partition_map_t& txn_partition_map = _get_txn_partition_map(transaction_id);
169
47.6k
    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
47.6k
    auto load_info = std::make_shared<TabletTxnInfo>(load_id, nullptr, ingest);
180
47.6k
    load_info->prepare();
181
47.6k
    if (!txn_tablet_map.contains(key)) {
182
6.05k
        g_tablet_txn_info_txn_partitions_count << 1;
183
6.05k
    }
184
47.6k
    txn_tablet_map[key][tablet_info] = std::move(load_info);
185
47.6k
    _insert_txn_partition_map_unlocked(transaction_id, partition_id);
186
47.6k
    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
47.6k
    return Status::OK();
190
47.6k
}
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
47.5k
                              const RowBinlogTxnInfo& attach_row_binlog) {
198
47.5k
    return commit_txn(tablet.data_dir()->get_meta(), partition_id, transaction_id,
199
47.5k
                      tablet.tablet_id(), tablet.tablet_uid(), load_id, rowset_ptr,
200
47.5k
                      std::move(guard), is_recovery, partial_update_info, attach_row_binlog);
201
47.5k
}
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
47.1k
                               const int64_t commit_tso) {
208
47.1k
    return publish_txn(tablet->data_dir()->get_meta(), partition_id, transaction_id,
209
47.1k
                       tablet->tablet_id(), tablet->tablet_uid(), version, stats,
210
47.1k
                       extend_tablet_txn_info, commit_tso);
211
47.1k
}
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
336
                              TTransactionId transaction_id) {
244
336
    return delete_txn(tablet->data_dir()->get_meta(), partition_id, transaction_id,
245
336
                      tablet->tablet_id(), tablet->tablet_uid());
246
336
}
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
33.3k
        std::shared_ptr<PartialUpdateInfo> partial_update_info) {
253
33.3k
    pair<int64_t, int64_t> key(partition_id, transaction_id);
254
33.3k
    TabletInfo tablet_info(tablet_id, tablet_uid);
255
256
33.3k
    std::lock_guard<std::shared_mutex> txn_lock(_get_txn_lock(transaction_id));
257
33.3k
    {
258
        // get tx
259
33.3k
        std::lock_guard<std::shared_mutex> wrlock(_get_txn_map_lock(transaction_id));
260
33.3k
        txn_tablet_map_t& txn_tablet_map = _get_txn_tablet_map(transaction_id);
261
33.3k
        auto it = txn_tablet_map.find(key);
262
33.3k
        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
33.3k
        auto load_itr = it->second.find(tablet_info);
268
33.3k
        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
33.3k
        auto& load_info = load_itr->second;
275
33.3k
        load_info->unique_key_merge_on_write = unique_key_merge_on_write;
276
33.3k
        load_info->delete_bitmap = delete_bitmap;
277
33.3k
        load_info->rowset_ids = rowset_ids;
278
33.3k
        load_info->partial_update_info = partial_update_info;
279
33.3k
    }
280
33.3k
}
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
47.7k
                              const RowBinlogTxnInfo& attach_row_binlog) {
289
47.7k
    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
47.7k
    pair<int64_t, int64_t> key(partition_id, transaction_id);
297
47.7k
    TabletInfo tablet_info(tablet_id, tablet_uid);
298
47.7k
    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
47.7k
    DBUG_EXECUTE_IF("TxnManager.commit_txn.random_failed", {
306
47.7k
        if (rand() % 100 < (100 * dp->param("percent", 0.5))) {
307
47.7k
            LOG_WARNING("TxnManager.commit_txn.random_failed")
308
47.7k
                    .tag("txn_id", transaction_id)
309
47.7k
                    .tag("tablet_id", tablet_id);
310
47.7k
            return Status::InternalError("debug commit txn random failed");
311
47.7k
        }
312
47.7k
    });
313
47.7k
    DBUG_EXECUTE_IF("TxnManager.commit_txn.wait", {
314
47.7k
        if (auto wait = dp->param<int>("duration", 0); wait > 0) {
315
47.7k
            LOG_WARNING("TxnManager.commit_txn.wait")
316
47.7k
                    .tag("txn_id", transaction_id)
317
47.7k
                    .tag("tablet_id", tablet_id)
318
47.7k
                    .tag("wait ms", wait);
319
47.7k
            std::this_thread::sleep_for(std::chrono::milliseconds(wait));
320
47.7k
        }
321
47.7k
    });
322
323
47.7k
    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
47.7k
    do {
326
        // get tx
327
47.7k
        std::shared_lock rdlock(_get_txn_map_lock(transaction_id));
328
47.7k
        auto rs_pb = rowset_ptr->rowset_meta()->get_rowset_pb();
329
        // TODO(dx): remove log after fix partition id eq 0 bug
330
47.7k
        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
47.7k
        txn_tablet_map_t& txn_tablet_map = _get_txn_tablet_map(transaction_id);
336
47.7k
        auto it = txn_tablet_map.find(key);
337
47.7k
        if (it == txn_tablet_map.end()) {
338
30
            break;
339
30
        }
340
341
47.7k
        auto load_itr = it->second.find(tablet_info);
342
47.7k
        if (load_itr == it->second.end()) {
343
116
            break;
344
116
        }
345
346
        // found load for txn,tablet
347
        // case 1: user commit rowset, then the load id must be equal
348
47.6k
        auto& load_info = load_itr->second;
349
        // check if load id is equal
350
47.6k
        if (load_info->rowset == nullptr) {
351
47.6k
            break;
352
47.6k
        }
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
47.7k
    if (!is_recovery) {
382
47.6k
        std::optional<BinlogFormatPB> binlog_format;
383
47.6k
        std::optional<RowsetMetaPB> attach_row_binlog_rowset_meta;
384
47.6k
        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
47.6k
        Status save_status = RowsetMetaManager::save(meta, tablet_uid, rowset_ptr->rowset_id(),
390
47.6k
                                                     rowset_ptr->rowset_meta()->get_rowset_pb(),
391
47.6k
                                                     binlog_format, attach_row_binlog_rowset_meta);
392
47.6k
        DBUG_EXECUTE_IF("TxnManager.RowsetMetaManager.save_wait", {
393
47.6k
            if (auto wait = dp->param<int>("duration", 0); wait > 0) {
394
47.6k
                LOG_WARNING("TxnManager.RowsetMetaManager.save_wait")
395
47.6k
                        .tag("txn_id", transaction_id)
396
47.6k
                        .tag("tablet_id", tablet_id)
397
47.6k
                        .tag("wait ms", wait);
398
47.6k
                std::this_thread::sleep_for(std::chrono::milliseconds(wait));
399
47.6k
            }
400
47.6k
        });
401
47.6k
        if (!save_status.ok()) {
402
0
            save_status.append(fmt::format(", txn id: {}", transaction_id));
403
0
            return save_status;
404
0
        }
405
406
47.6k
        if (partial_update_info && partial_update_info->is_partial_update()) {
407
478
            PartialUpdateInfoPB partial_update_info_pb;
408
478
            partial_update_info->to_pb(&partial_update_info_pb);
409
478
            save_status = RowsetMetaManager::save_partial_update_info(
410
478
                    meta, tablet_id, partition_id, transaction_id, partial_update_info_pb);
411
478
            if (!save_status.ok()) {
412
0
                save_status.append(fmt::format(", txn_id: {}", transaction_id));
413
0
                return save_status;
414
0
            }
415
478
        }
416
47.6k
    }
417
418
47.7k
    TabletSharedPtr tablet;
419
47.7k
    std::shared_ptr<PartialUpdateInfo> decoded_partial_update_info {nullptr};
420
47.7k
    if (is_recovery) {
421
134
        tablet = _engine.tablet_manager()->get_tablet(tablet_id, tablet_uid);
422
134
        if (tablet != nullptr && tablet->enable_unique_key_merge_on_write()) {
423
6
            PartialUpdateInfoPB partial_update_info_pb;
424
6
            auto st = RowsetMetaManager::try_get_partial_update_info(
425
6
                    meta, tablet_id, partition_id, transaction_id, &partial_update_info_pb);
426
6
            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
6
            } else if (!st.is<META_KEY_NOT_FOUND>()) {
431
                // the load is not a partial update
432
0
                return st;
433
0
            }
434
6
        }
435
134
    }
436
437
47.7k
    {
438
47.7k
        std::lock_guard<std::shared_mutex> wrlock(_get_txn_map_lock(transaction_id));
439
47.7k
        auto load_info = std::make_shared<TabletTxnInfo>(load_id, rowset_ptr);
440
47.7k
        load_info->attach_row_binlog = attach_row_binlog;
441
        // resolve the independent binlog tablet in advance for the later publish phase.
442
47.7k
        if (load_info->attach_row_binlog.rowset != nullptr &&
443
47.7k
            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
47.7k
        load_info->pending_rs_guard = std::move(guard);
455
47.7k
        if (is_recovery) {
456
134
            if (tablet != nullptr && tablet->enable_unique_key_merge_on_write()) {
457
6
                load_info->unique_key_merge_on_write = true;
458
6
                load_info->delete_bitmap.reset(new DeleteBitmap(tablet->tablet_id()));
459
6
                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
6
            }
468
134
        }
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
47.7k
        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
47.7k
        load_info->commit();
480
481
47.7k
        txn_tablet_map_t& txn_tablet_map = _get_txn_tablet_map(transaction_id);
482
47.7k
        txn_tablet_map[key][tablet_info] = std::move(load_info);
483
47.7k
        _insert_txn_partition_map_unlocked(transaction_id, partition_id);
484
47.7k
        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
47.7k
    }
490
0
    return Status::OK();
491
47.7k
}
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
47.2k
                               const int64_t commit_tso) {
500
47.2k
    auto tablet = _engine.tablet_manager()->get_tablet(tablet_id);
501
47.2k
    if (tablet == nullptr) {
502
0
        return Status::OK();
503
0
    }
504
47.2k
    DCHECK(stats != nullptr);
505
506
47.2k
    pair<int64_t, int64_t> key(partition_id, transaction_id);
507
47.2k
    TabletInfo tablet_info(tablet_id, tablet_uid);
508
47.2k
    RowsetSharedPtr rowset;
509
47.2k
    std::shared_ptr<TabletTxnInfo> tablet_txn_info;
510
47.2k
    int64_t t1 = MonotonicMicros();
511
    /// Step 1: get rowset, tablet_txn_info by key
512
47.2k
    {
513
47.2k
        std::shared_lock txn_rlock(_get_txn_lock(transaction_id));
514
47.2k
        std::shared_lock txn_map_rlock(_get_txn_map_lock(transaction_id));
515
47.2k
        stats->lock_wait_time_us += MonotonicMicros() - t1;
516
517
47.2k
        txn_tablet_map_t& txn_tablet_map = _get_txn_tablet_map(transaction_id);
518
47.2k
        if (auto it = txn_tablet_map.find(key); it != txn_tablet_map.end()) {
519
47.1k
            auto& tablet_map = it->second;
520
47.1k
            if (auto txn_info_iter = tablet_map.find(tablet_info);
521
47.1k
                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
47.1k
                tablet_txn_info = txn_info_iter->second;
525
47.1k
                extend_tablet_txn_info = tablet_txn_info;
526
47.1k
                rowset = tablet_txn_info->rowset;
527
47.1k
            }
528
47.1k
        }
529
47.2k
    }
530
47.2k
    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
47.2k
    DBUG_EXECUTE_IF("TxnManager.publish_txn.random_failed_before_save_rs_meta", {
537
47.2k
        if (rand() % 100 < (100 * dp->param("percent", 0.5))) {
538
47.2k
            LOG_WARNING("TxnManager.publish_txn.random_failed_before_save_rs_meta")
539
47.2k
                    .tag("txn_id", transaction_id)
540
47.2k
                    .tag("tablet_id", tablet_id);
541
47.2k
            return Status::InternalError("debug publish txn before save rs meta random failed");
542
47.2k
        }
543
47.2k
    });
544
47.2k
    DBUG_EXECUTE_IF("TxnManager.publish_txn.wait_before_save_rs_meta", {
545
47.2k
        if (auto wait = dp->param<int>("duration", 0); wait > 0) {
546
47.2k
            LOG_WARNING("TxnManager.publish_txn.wait_before_save_rs_meta")
547
47.2k
                    .tag("txn_id", transaction_id)
548
47.2k
                    .tag("tablet_id", tablet_id)
549
47.2k
                    .tag("wait ms", wait);
550
47.2k
            std::this_thread::sleep_for(std::chrono::milliseconds(wait));
551
47.2k
        }
552
47.2k
    });
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
47.2k
    rowset->make_visible(version, commit_tso);
560
561
    // Make the attached binlog rowset visible together.
562
47.2k
    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
47.2k
    DBUG_EXECUTE_IF("TxnManager.publish_txn.random_failed_after_save_rs_meta", {
567
47.2k
        if (rand() % 100 < (100 * dp->param("percent", 0.5))) {
568
47.2k
            LOG_WARNING("TxnManager.publish_txn.random_failed_after_save_rs_meta")
569
47.2k
                    .tag("txn_id", transaction_id)
570
47.2k
                    .tag("tablet_id", tablet_id);
571
47.2k
            return Status::InternalError("debug publish txn after save rs meta random failed");
572
47.2k
        }
573
47.2k
    });
574
47.2k
    DBUG_EXECUTE_IF("TxnManager.publish_txn.wait_after_save_rs_meta", {
575
47.2k
        if (auto wait = dp->param<int>("duration", 0); wait > 0) {
576
47.2k
            LOG_WARNING("TxnManager.publish_txn.wait_after_save_rs_meta")
577
47.2k
                    .tag("txn_id", transaction_id)
578
47.2k
                    .tag("tablet_id", tablet_id)
579
47.2k
                    .tag("wait ms", wait);
580
47.2k
            std::this_thread::sleep_for(std::chrono::milliseconds(wait));
581
47.2k
        }
582
47.2k
    });
583
    // update delete_bitmap
584
47.2k
    if (tablet_txn_info->unique_key_merge_on_write) {
585
33.2k
        int64_t t2 = MonotonicMicros();
586
33.2k
        if (rowset->num_segments() > 1 &&
587
33.2k
            !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
33.2k
        RETURN_IF_ERROR(
598
33.2k
                Tablet::update_delete_bitmap(tablet, tablet_txn_info.get(), transaction_id));
599
33.2k
        int64_t t3 = MonotonicMicros();
600
33.2k
        stats->calc_delete_bitmap_time_us = t3 - t2;
601
33.2k
        RETURN_IF_ERROR(TabletMetaManager::save_delete_bitmap(
602
33.2k
                tablet->data_dir(), tablet->tablet_id(), tablet_txn_info->delete_bitmap,
603
33.2k
                version.second));
604
33.2k
        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
33.2k
        stats->save_meta_time_us = MonotonicMicros() - t3;
617
33.2k
    }
618
619
    /// Step 3:  add to binlog
620
47.2k
    std::optional<BinlogFormatPB> binlog_format;
621
47.2k
    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
47.2k
    std::optional<RowsetMetaPB> attach_row_binlog_rowset_meta;
634
47.2k
    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
47.2k
    int64_t t5 = MonotonicMicros();
642
47.2k
    auto status = RowsetMetaManager::save(meta, tablet_uid, rowset->rowset_id(),
643
47.2k
                                          rowset->rowset_meta()->get_rowset_pb(), binlog_format,
644
47.2k
                                          attach_row_binlog_rowset_meta);
645
47.2k
    stats->save_meta_time_us += MonotonicMicros() - t5;
646
47.2k
    if (!status.ok()) {
647
0
        status.append(fmt::format(", txn id: {}", transaction_id));
648
0
        return status;
649
0
    }
650
651
47.2k
    if (tablet_txn_info->unique_key_merge_on_write && tablet_txn_info->partial_update_info &&
652
47.2k
        tablet_txn_info->partial_update_info->is_partial_update()) {
653
478
        status = RowsetMetaManager::remove_partial_update_info(meta, tablet_id, partition_id,
654
478
                                                               transaction_id);
655
478
        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
478
    }
664
665
    // TODO(Drogon): remove these test codes
666
47.2k
    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
47.2k
    int64_t t6 = MonotonicMicros();
675
47.2k
    std::lock_guard<std::shared_mutex> txn_lock(_get_txn_lock(transaction_id));
676
47.2k
    std::lock_guard<std::shared_mutex> wrlock(_get_txn_map_lock(transaction_id));
677
47.2k
    stats->lock_wait_time_us += MonotonicMicros() - t6;
678
47.2k
    _remove_txn_tablet_info_unlocked(partition_id, transaction_id, tablet_id, tablet_uid, txn_lock,
679
47.2k
                                     wrlock);
680
18.4E
    VLOG_NOTICE << "publish txn successfully."
681
18.4E
                << " partition_id: " << key.first << ", txn_id: " << key.second
682
18.4E
                << ", tablet_id: " << tablet_info.tablet_id << ", rowsetid: " << rowset->rowset_id()
683
18.4E
                << ", version: " << version.first << "," << version.second;
684
47.2k
    return status;
685
47.2k
}
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
47.2k
                                                  std::lock_guard<std::shared_mutex>& wrlock) {
692
47.2k
    std::pair<int64_t, int64_t> key {partition_id, transaction_id};
693
47.2k
    TabletInfo tablet_info {tablet_id, tablet_uid};
694
47.2k
    txn_tablet_map_t& txn_tablet_map = _get_txn_tablet_map(transaction_id);
695
47.2k
    if (auto it = txn_tablet_map.find(key); it != txn_tablet_map.end()) {
696
47.2k
        it->second.erase(tablet_info);
697
47.2k
        if (it->second.empty()) {
698
6.01k
            txn_tablet_map.erase(it);
699
6.01k
            g_tablet_txn_info_txn_partitions_count << -1;
700
6.01k
            _clear_txn_partition_map_unlocked(transaction_id, partition_id);
701
6.01k
        }
702
47.2k
    }
703
47.2k
}
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
341
                              TabletUid tablet_uid) {
760
341
    pair<int64_t, int64_t> key(partition_id, transaction_id);
761
341
    TabletInfo tablet_info(tablet_id, tablet_uid);
762
341
    std::lock_guard<std::shared_mutex> txn_wrlock(_get_txn_map_lock(transaction_id));
763
341
    txn_tablet_map_t& txn_tablet_map = _get_txn_tablet_map(transaction_id);
764
341
    auto it = txn_tablet_map.find(key);
765
341
    if (it == txn_tablet_map.end()) {
766
0
        return Status::Error<TRANSACTION_NOT_EXIST>("key not founded from txn_tablet_map");
767
0
    }
768
341
    Status st = Status::OK();
769
341
    auto load_itr = it->second.find(tablet_info);
770
341
    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
341
        auto& load_info = load_itr->second;
774
341
        auto& rowset = load_info->rowset;
775
341
        if (rowset != nullptr && meta != nullptr) {
776
340
            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
339
            } else {
785
339
                const auto& attach_binlog_rowset = load_info->attach_row_binlog.rowset;
786
339
                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
339
                static_cast<void>(RowsetMetaManager::remove(meta, tablet_uid, rowset->rowset_id()));
793
339
#ifndef BE_TEST
794
339
                _engine.add_unused_rowset(rowset);
795
339
#endif
796
339
                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
339
            }
805
340
        }
806
341
        it->second.erase(load_itr);
807
341
    }
808
341
    if (it->second.empty()) {
809
21
        txn_tablet_map.erase(it);
810
21
        g_tablet_txn_info_txn_partitions_count << -1;
811
21
        _clear_txn_partition_map_unlocked(transaction_id, partition_id);
812
21
    }
813
341
    return st;
814
341
}
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
5.71k
                                                    TabletUid tablet_uid) {
845
5.71k
    TabletInfo tablet_info(tablet_id, tablet_uid);
846
5.63M
    for (int32_t i = 0; i < _txn_map_shard_size; i++) {
847
5.62M
        std::lock_guard<std::shared_mutex> txn_wrlock(_txn_map_locks[i]);
848
5.62M
        txn_tablet_map_t& txn_tablet_map = _txn_tablet_maps[i];
849
5.63M
        for (auto it = txn_tablet_map.begin(); it != txn_tablet_map.end();) {
850
14.5k
            auto load_itr = it->second.find(tablet_info);
851
14.5k
            if (load_itr != it->second.end()) {
852
22
                auto& load_info = load_itr->second;
853
22
                auto& rowset = load_info->rowset;
854
22
                const auto& attach_binlog_rowset = load_info->attach_row_binlog.rowset;
855
22
                if (rowset != nullptr && meta != nullptr) {
856
22
                    LOG(INFO) << " delete transaction from engine "
857
22
                              << ", tablet: " << tablet_info.to_string()
858
22
                              << ", rowset id: " << rowset->rowset_id();
859
                    // clean the attached binlog rowset first
860
22
                    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
22
                    static_cast<void>(
871
22
                            RowsetMetaManager::remove(meta, tablet_uid, rowset->rowset_id()));
872
22
                }
873
22
                LOG(INFO) << "remove tablet related txn."
874
22
                          << " partition_id: " << it->first.first
875
22
                          << ", transaction_id: " << it->first.second
876
22
                          << ", tablet: " << tablet_info.to_string() << ", rowset: "
877
22
                          << (rowset != nullptr ? rowset->rowset_id().to_string() : "0")
878
22
                          << ", binlog<row> rowset: "
879
22
                          << (attach_binlog_rowset != nullptr
880
22
                                      ? attach_binlog_rowset->rowset_id().to_string()
881
22
                                      : "0");
882
22
                it->second.erase(load_itr);
883
22
            }
884
14.5k
            if (it->second.empty()) {
885
4
                _clear_txn_partition_map_unlocked(it->first.second, it->first.first);
886
4
                it = txn_tablet_map.erase(it);
887
4
                g_tablet_txn_info_txn_partitions_count << -1;
888
14.5k
            } else {
889
14.5k
                ++it;
890
14.5k
            }
891
14.5k
        }
892
5.62M
    }
893
5.71k
    if (meta != nullptr) {
894
5.71k
        Status st = RowsetMetaManager::remove_tablet_related_partial_update_info(meta, tablet_id);
895
5.71k
        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
5.71k
    }
900
5.71k
}
901
902
void TxnManager::get_txn_related_tablets(
903
        const TTransactionId transaction_id, TPartitionId partition_id,
904
        std::map<TabletInfo, RowsetSharedPtr>* tablet_infos,
905
6.05k
        std::map<TabletInfo, std::shared_ptr<TabletTxnInfo>>* tablet_txn_infos) {
906
    // get tablets in this transaction
907
6.05k
    pair<int64_t, int64_t> key(partition_id, transaction_id);
908
6.05k
    std::shared_lock txn_rdlock(_get_txn_map_lock(transaction_id));
909
6.05k
    txn_tablet_map_t& txn_tablet_map = _get_txn_tablet_map(transaction_id);
910
6.05k
    auto it = txn_tablet_map.find(key);
911
6.05k
    if (it == txn_tablet_map.end()) {
912
2
        VLOG_NOTICE << "could not find tablet for"
913
1
                    << " partition_id=" << partition_id << ", transaction_id=" << transaction_id;
914
2
        return;
915
2
    }
916
6.05k
    auto& load_info_map = it->second;
917
918
    // each tablet
919
47.6k
    for (auto& load_info : load_info_map) {
920
47.6k
        const TabletInfo& tablet_info = load_info.first;
921
        // must not check rowset == null here, because if rowset == null
922
        // publish version should failed
923
47.6k
        tablet_infos->emplace(tablet_info, load_info.second->rowset);
924
47.6k
        if (tablet_txn_infos != nullptr) {
925
47.2k
            tablet_txn_infos->emplace(tablet_info, load_info.second);
926
47.2k
        }
927
47.6k
    }
928
6.05k
}
929
930
58
void TxnManager::get_all_related_tablets(std::set<TabletInfo>* tablet_infos) {
931
59.4k
    for (int32_t i = 0; i < _txn_map_shard_size; i++) {
932
59.3k
        std::shared_lock txn_rdlock(_txn_map_locks[i]);
933
59.3k
        for (auto& it : _txn_tablet_maps[i]) {
934
1.10k
            for (auto& tablet_load_it : it.second) {
935
1.10k
                tablet_infos->emplace(tablet_load_it.first);
936
1.10k
            }
937
76
        }
938
59.3k
    }
939
58
}
940
941
void TxnManager::get_all_commit_tablet_txn_info_by_tablet(
942
3.24k
        const Tablet& tablet, CommitTabletTxnInfoVec* commit_tablet_txn_info_vec) {
943
3.25M
    for (int32_t i = 0; i < _txn_map_shard_size; i++) {
944
3.24M
        std::shared_lock txn_rdlock(_txn_map_locks[i]);
945
3.24M
        for (const auto& [txn_key, load_info_map] : _txn_tablet_maps[i]) {
946
1.09k
            auto tablet_load_it = load_info_map.find(tablet.get_tablet_info());
947
1.09k
            if (tablet_load_it != load_info_map.end()) {
948
86
                const auto& [_, load_info] = *tablet_load_it;
949
86
                const auto& rowset = load_info->rowset;
950
86
                const auto& delete_bitmap = load_info->delete_bitmap;
951
86
                if (!rowset || !delete_bitmap) {
952
75
                    continue;
953
75
                }
954
11
                commit_tablet_txn_info_vec->push_back({
955
11
                        .transaction_id = txn_key.second,
956
11
                        .partition_id = txn_key.first,
957
11
                        .delete_bitmap = delete_bitmap,
958
11
                        .rowset_ids = load_info->rowset_ids,
959
11
                        .partial_update_info = load_info->partial_update_info,
960
11
                });
961
11
            }
962
1.09k
        }
963
3.24M
    }
964
3.24k
}
965
966
160
void TxnManager::build_expire_txn_map(std::map<TabletInfo, std::vector<int64_t>>* expire_txn_map) {
967
160
    int64_t now = UnixSeconds();
968
    // traverse the txn map, and get all expired txns
969
164k
    for (int32_t i = 0; i < _txn_map_shard_size; i++) {
970
163k
        std::shared_lock txn_rdlock(_txn_map_locks[i]);
971
163k
        for (auto&& [txn_key, tablet_txn_infos] : _txn_tablet_maps[i]) {
972
205
            auto txn_id = txn_key.second;
973
3.14k
            for (auto&& [tablet_info, txn_info] : tablet_txn_infos) {
974
3.14k
                double diff = difftime(now, txn_info->creation_time);
975
3.14k
                if (diff < config::pending_data_expire_time_sec) {
976
3.06k
                    continue;
977
3.06k
                }
978
979
84
                (*expire_txn_map)[tablet_info].push_back(txn_id);
980
84
                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
84
            }
986
205
        }
987
163k
    }
988
160
}
989
990
void TxnManager::get_partition_ids(const TTransactionId transaction_id,
991
14
                                   std::vector<TPartitionId>* partition_ids) {
992
14
    std::shared_lock txn_rdlock(_get_txn_map_lock(transaction_id));
993
14
    txn_partition_map_t& txn_partition_map = _get_txn_partition_map(transaction_id);
994
14
    auto it = txn_partition_map.find(transaction_id);
995
14
    if (it != txn_partition_map.end()) {
996
13
        for (int64_t partition_id : it->second) {
997
13
            partition_ids->push_back(partition_id);
998
13
        }
999
13
    }
1000
14
}
1001
1002
95.3k
void TxnManager::_insert_txn_partition_map_unlocked(int64_t transaction_id, int64_t partition_id) {
1003
95.3k
    txn_partition_map_t& txn_partition_map = _get_txn_partition_map(transaction_id);
1004
95.3k
    auto find = txn_partition_map.find(transaction_id);
1005
95.3k
    if (find == txn_partition_map.end()) {
1006
6.04k
        txn_partition_map[transaction_id] = std::unordered_set<int64_t>();
1007
6.04k
    }
1008
95.3k
    txn_partition_map[transaction_id].insert(partition_id);
1009
95.3k
}
1010
1011
6.04k
void TxnManager::_clear_txn_partition_map_unlocked(int64_t transaction_id, int64_t partition_id) {
1012
6.04k
    txn_partition_map_t& txn_partition_map = _get_txn_partition_map(transaction_id);
1013
6.04k
    auto it = txn_partition_map.find(transaction_id);
1014
6.04k
    if (it != txn_partition_map.end()) {
1015
6.04k
        it->second.erase(partition_id);
1016
6.04k
        if (it->second.empty()) {
1017
6.01k
            txn_partition_map.erase(it);
1018
6.01k
        }
1019
6.04k
    }
1020
6.04k
}
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
33.3k
int64_t TxnManager::get_txn_by_tablet_version(int64_t tablet_id, int64_t version) {
1070
33.3k
    char key[16];
1071
33.3k
    memcpy(key, &tablet_id, sizeof(int64_t));
1072
33.3k
    memcpy(key + sizeof(int64_t), &version, sizeof(int64_t));
1073
33.3k
    CacheKey cache_key((const char*)&key, sizeof(key));
1074
1075
33.3k
    auto* handle = _tablet_version_cache->lookup(cache_key);
1076
33.3k
    if (handle == nullptr) {
1077
33.3k
        return -1;
1078
33.3k
    }
1079
29
    int64_t res = ((CacheValue*)_tablet_version_cache->value(handle))->value;
1080
29
    _tablet_version_cache->release(handle);
1081
29
    return res;
1082
33.3k
}
1083
1084
33.3k
void TxnManager::update_tablet_version_txn(int64_t tablet_id, int64_t version, int64_t txn_id) {
1085
33.3k
    char key[16];
1086
33.3k
    memcpy(key, &tablet_id, sizeof(int64_t));
1087
33.3k
    memcpy(key + sizeof(int64_t), &version, sizeof(int64_t));
1088
33.3k
    CacheKey cache_key((const char*)&key, sizeof(key));
1089
1090
33.3k
    auto* value = new CacheValue;
1091
33.3k
    value->value = txn_id;
1092
33.3k
    auto* handle = _tablet_version_cache->insert(cache_key, value, 1, sizeof(txn_id),
1093
33.3k
                                                 CachePriority::NORMAL);
1094
33.3k
    _tablet_version_cache->release(handle);
1095
33.3k
}
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