Skip to content

Commit

Permalink
fix(mvcc): fix commit xid may be accidentally reused (#26)
Browse files Browse the repository at this point in the history
**问题:** 在事务恢复阶段,`MTR_BEGIN` 日志对应的 trx id 会在 `MvccTrxManager` 类的
`create_trx(int32_t trx_id)` 方法中更新 `current_trx_id` 以避免重复使用,符合预期。但是
`MTR_COMMIT` 日志所使用的 commit xid 没有更新,可能会被重用而导致错误的结果。

**解决方案:** 增加 `update_trx_id` 方法用于确保 `current_trx_id` 不小于给定的参数。在 recover
阶段,`MvccTrx` 提交时应当调用该方法更新 `current_trx_id`。
  • Loading branch information
hotwords123 authored Jun 12, 2024
1 parent 328df69 commit d4f8684
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/server/include/storage_engine/transaction/mvcc_trx.h
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ class MvccTrxManager : public TrxManager
int32_t next_trx_id();
int32_t max_trx_id() const;

// 在 recover 场景下使用,确保当前事务 id 不小于 trx_id
void update_trx_id(int32_t trx_id);

private:
std::vector<FieldMeta> fields_; // 存储事务数据需要用到的字段元数据,所有表结构都需要带
std::atomic<int32_t> current_trx_id_{0};
Expand Down
11 changes: 11 additions & 0 deletions src/server/storage_engine/transaction/mvcc_trx.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,12 @@ int32_t MvccTrxManager::max_trx_id() const
return numeric_limits<int32_t>::max();
}

void MvccTrxManager::update_trx_id(int32_t trx_id)
{
int32_t old_trx_id = current_trx_id_;
while (old_trx_id < trx_id && !current_trx_id_.compare_exchange_weak(old_trx_id, trx_id));
}

////////////////////////////////////////////////////////////////////////////////
MvccTrx::MvccTrx(MvccTrxManager &kit, LogManager *log_manager) : trx_kit_(kit), log_manager_(log_manager)
{}
Expand Down Expand Up @@ -168,6 +174,11 @@ RC MvccTrx::commit_with_trx_id(int32_t commit_xid)
RC rc = RC::SUCCESS;
started_ = false;

if (recovering_) {
// 在事务恢复时,更新当前事务 id 避免被后续事务重用
trx_kit_.update_trx_id(commit_xid);
}

for (const Operation &operation : operations_) {
switch (operation.type()) {
case Operation::Type::INSERT: {
Expand Down

0 comments on commit d4f8684

Please sign in to comment.