diff --git a/src/sdk/rpc/brpc/unary_rpc.h b/src/sdk/rpc/brpc/unary_rpc.h index fad280b..6060f4c 100644 --- a/src/sdk/rpc/brpc/unary_rpc.h +++ b/src/sdk/rpc/brpc/unary_rpc.h @@ -183,7 +183,11 @@ class UnaryRpc : public Rpc { } } - brpc_ctx->cb(); + // Move the callback onto this frame before invoking: the chain may + // release the last owner of this rpc, so neither the callback storage nor + // any other member may be touched once it starts running. + RpcCallback cb = std::move(brpc_ctx->cb); + cb(); } void Reset() override { diff --git a/src/sdk/rpc/grpc/unary_rpc.h b/src/sdk/rpc/grpc/unary_rpc.h index aaf1bf8..6cad7c3 100644 --- a/src/sdk/rpc/grpc/unary_rpc.h +++ b/src/sdk/rpc/grpc/unary_rpc.h @@ -115,7 +115,11 @@ class UnaryRpc : public Rpc { } TraceRpcPerformance(end_time - start_time, Method(), context->peer(), str); - grpc_ctx->cb(); + // Move the callback onto this frame before invoking: the chain may + // release the last owner of this rpc, so neither the callback storage nor + // any other member may be touched once it starts running. + RpcCallback cb = std::move(grpc_ctx->cb); + cb(); } void Reset() override { diff --git a/src/sdk/rpc/store_rpc_controller.h b/src/sdk/rpc/store_rpc_controller.h index 9b8800a..651fffc 100644 --- a/src/sdk/rpc/store_rpc_controller.h +++ b/src/sdk/rpc/store_rpc_controller.h @@ -15,7 +15,9 @@ #ifndef DINGODB_SDK_STORE_RPC_CONTROLLER_H_ #define DINGODB_SDK_STORE_RPC_CONTROLLER_H_ +#include #include +#include #include "dingosdk/status.h" #include "proto/error.pb.h" @@ -98,6 +100,22 @@ class StoreRpcController { StatusCallback call_back_; }; +// One retry round of fan-out store rpcs. Tasks that retry by re-running +// DoAsync must keep each round's rpcs/controllers in a StoreRpcRound owned by +// the AsyncCall callbacks (capture the shared_ptr by value), never in task +// members that the next round clears: a zero-delay retry round runs while the +// previous round's issuing frame and callback chains are still on other +// threads' stacks. pending must be set to rpcs.size() + 1 before issuing; the +// extra count is released by the issuing frame after its last use of task +// state, so the task cannot complete (and be destroyed) underneath that frame. +// See TxnBatchGetTask for the reference usage. +template +struct StoreRpcRound { + std::vector> rpcs; + std::vector controllers; + std::atomic pending{0}; +}; + } // namespace sdk } // namespace dingodb diff --git a/src/sdk/transaction/txn_task/txn_batch_get_task.cc b/src/sdk/transaction/txn_task/txn_batch_get_task.cc index ff48950..8ba8c8e 100644 --- a/src/sdk/transaction/txn_task/txn_batch_get_task.cc +++ b/src/sdk/transaction/txn_task/txn_batch_get_task.cc @@ -47,25 +47,37 @@ Status TxnBatchGetTask::Init() { } void TxnBatchGetTask::DoAsync() { + // Owns this frame's +1 pending count. Declared before the tracer cleanup so + // it runs after it (reverse destruction order): once released, the last + // finished sub task may complete the task and destroy it, so nothing may + // touch task state afterwards. + std::shared_ptr round; + SCOPED_CLEANUP({ + if (round) { + FinishSubTask(round); + } + }); + auto start_time = TimestampUs(); SCOPED_CLEANUP(txn_impl_->GetTracer()->IncrementReadSdkTime(TimestampUs() - start_time);); std::set next_batch; + std::unordered_map resolved_locks; { WriteLockGuard guard(rw_lock_); next_batch = next_keys_; need_retry_ = false; status_ = Status::OK(); + resolved_locks.swap(region_id_to_resolved_lock_); } if (next_batch.empty()) { - DoAsyncDone(Status::OK()); + // completes via the round release above + round = std::make_shared(); + round->pending.store(1); return; } - rpcs_.clear(); - controllers_.clear(); - std::unordered_map> region_id_to_region; std::unordered_map> region_id_to_keys; @@ -74,7 +86,13 @@ void TxnBatchGetTask::DoAsync() { std::shared_ptr tmp; Status s = meta_cache->LookupRegionByKey(key, tmp); if (!s.ok()) { - DoAsyncDone(s); + { + WriteLockGuard guard(rw_lock_); + status_ = s; + need_retry_ = false; + } + round = std::make_shared(); + round->pending.store(1); return; } auto iter = region_id_to_region.find(tmp->RegionId()); @@ -84,8 +102,9 @@ void TxnBatchGetTask::DoAsync() { region_id_to_keys[tmp->RegionId()].push_back(key); } - controllers_.reserve(region_id_to_keys.size()); - rpcs_.reserve(region_id_to_keys.size()); + round = std::make_shared(); + round->controllers.reserve(region_id_to_keys.size()); + round->rpcs.reserve(region_id_to_keys.size()); for (const auto& entry : region_id_to_keys) { auto region_id = entry.first; auto iter = region_id_to_region.find(region_id); @@ -93,8 +112,9 @@ void TxnBatchGetTask::DoAsync() { auto region = iter->second; uint64_t resolved_lock = 0; - if (region_id_to_resolved_lock_.find(region_id) != region_id_to_resolved_lock_.end()) { - resolved_lock = region_id_to_resolved_lock_[region_id]; + auto resolved_iter = resolved_locks.find(region_id); + if (resolved_iter != resolved_locks.end()) { + resolved_lock = resolved_iter->second; } auto rpc = std::make_shared(); @@ -106,21 +126,24 @@ void TxnBatchGetTask::DoAsync() { for (const auto& key : entry.second) { *rpc->MutableRequest()->add_keys() = key; } - controllers_.emplace_back(stub, rpc, region); - rpcs_.push_back(rpc); + round->controllers.emplace_back(stub, rpc, region); + round->rpcs.push_back(rpc); } - CHECK(rpcs_.size() == controllers_.size()); - sub_tasks_count_.store(rpcs_.size()); - - region_id_to_resolved_lock_.clear(); - - for (int i = 0; i < rpcs_.size(); ++i) { - auto& controller = controllers_[i]; - controller.AsyncCall([this, rpc = rpcs_[i].get()](const Status& s) { TxnBatchGetRpcCallback(s, rpc); }); + CHECK(round->rpcs.size() == round->controllers.size()); + // +1 for this issuing frame, released by the scoped cleanup above + round->pending.store(static_cast(round->rpcs.size()) + 1); + + for (size_t i = 0; i < round->rpcs.size(); ++i) { + auto& controller = round->controllers[i]; + // round is captured by value: the callbacks collectively keep this + // round's rpcs/controllers alive until every chain fully unwinds + controller.AsyncCall( + [this, round, rpc = round->rpcs[i].get()](const Status& s) { TxnBatchGetRpcCallback(round, s, rpc); }); } } -void TxnBatchGetTask::TxnBatchGetRpcCallback(const Status& status, TxnBatchGetRpc* rpc) { +void TxnBatchGetTask::TxnBatchGetRpcCallback(const std::shared_ptr& round, const Status& status, + TxnBatchGetRpc* rpc) { DINGO_LOG(DEBUG) << fmt::format("[sdk.txn.{}] rpc: {} request: {} response: {}", txn_impl_->ID(), rpc->Method(), rpc->Request()->ShortDebugString(), rpc->Response()->ShortDebugString()); @@ -131,6 +154,7 @@ void TxnBatchGetTask::TxnBatchGetRpcCallback(const Status& status, TxnBatchGetRp Status s; bool need_retry = false; + uint64_t resolved_lock_ts = 0; const auto* response = rpc->Response(); if (!status.ok()) { DINGO_LOG(WARNING) << fmt::format("[sdk.txn.{}] rpc: {} send to region: {} fail: {}", txn_impl_->ID(), @@ -145,8 +169,7 @@ void TxnBatchGetTask::TxnBatchGetRpcCallback(const Status& status, TxnBatchGetRp if (s.ok()) { need_retry = true; } else if (s.IsPushMinCommitTs()) { - region_id_to_resolved_lock_[rpc->Request()->context().region_id()] = - response->txn_result().locked().lock_ts(); + resolved_lock_ts = response->txn_result().locked().lock_ts(); need_retry = true; s = Status::OK(); } @@ -172,6 +195,9 @@ void TxnBatchGetTask::TxnBatchGetRpcCallback(const Status& status, TxnBatchGetRp } } else { need_retry_ = true; + if (resolved_lock_ts != 0) { + region_id_to_resolved_lock_[rpc->Request()->context().region_id()] = resolved_lock_ts; + } } } else { if (status_.ok()) { @@ -184,21 +210,27 @@ void TxnBatchGetTask::TxnBatchGetRpcCallback(const Status& status, TxnBatchGetRp } } - if (sub_tasks_count_.fetch_sub(1) == 1) { - Status tmp; - bool tmp_need_retry = false; - { - ReadLockGuard guard(rw_lock_); - tmp = status_; - tmp_need_retry = need_retry_; - } - if (tmp.ok() && tmp_need_retry) { - txn_impl_->GetTracer()->IncrementReadRetryCount(1); - DoAsyncRetry(); - return; - } - DoAsyncDone(tmp); + FinishSubTask(round); +} + +void TxnBatchGetTask::FinishSubTask(const std::shared_ptr& round) { + if (round->pending.fetch_sub(1) != 1) { + return; + } + + Status tmp; + bool tmp_need_retry = false; + { + ReadLockGuard guard(rw_lock_); + tmp = status_; + tmp_need_retry = need_retry_; + } + if (tmp.ok() && tmp_need_retry) { + txn_impl_->GetTracer()->IncrementReadRetryCount(1); + DoAsyncRetry(); + return; } + DoAsyncDone(tmp); } } // namespace sdk diff --git a/src/sdk/transaction/txn_task/txn_batch_get_task.h b/src/sdk/transaction/txn_task/txn_batch_get_task.h index 8169306..b016e87 100644 --- a/src/sdk/transaction/txn_task/txn_batch_get_task.h +++ b/src/sdk/transaction/txn_task/txn_batch_get_task.h @@ -49,7 +49,12 @@ class TxnBatchGetTask : public TxnTask { std::string Name() const override { return "TxnBatchGetTask"; } - void TxnBatchGetRpcCallback(const Status& status, TxnBatchGetRpc* rpc); + using Round = StoreRpcRound; + + void TxnBatchGetRpcCallback(const std::shared_ptr& round, const Status& status, TxnBatchGetRpc* rpc); + + // drops one pending count of the round; the last owner decides retry/done + void FinishSubTask(const std::shared_ptr& round); const std::vector& keys_; std::vector& out_kvs_; @@ -57,16 +62,13 @@ class TxnBatchGetTask : public TxnTask { std::set next_keys_; std::shared_ptr txn_impl_; + // guarded by rw_lock_ std::unordered_map region_id_to_resolved_lock_; - std::vector controllers_; - std::vector> rpcs_; bool need_retry_{false}; RWLock rw_lock_; Status status_; - - std::atomic sub_tasks_count_{0}; }; } // namespace sdk diff --git a/src/sdk/transaction/txn_task/txn_commit_task.cc b/src/sdk/transaction/txn_task/txn_commit_task.cc index 4921c5b..e2b2f6e 100644 --- a/src/sdk/transaction/txn_task/txn_commit_task.cc +++ b/src/sdk/transaction/txn_task/txn_commit_task.cc @@ -53,6 +53,17 @@ Status TxnCommitTask::Init() { } void TxnCommitTask::DoAsync() { + // Owns this frame's +1 pending count. Declared before the tracer cleanup so + // it runs after it (reverse destruction order): once released, the last + // finished sub task may complete the task and destroy it, so nothing may + // touch task state afterwards. + std::shared_ptr round; + SCOPED_CLEANUP({ + if (round) { + FinishSubTask(round); + } + }); + auto start_time = TimestampUs(); SCOPED_CLEANUP(txn_impl_->GetTracer()->IncrementCommitSdkTime(TimestampUs() - start_time);); std::set next_batch; @@ -63,13 +74,12 @@ void TxnCommitTask::DoAsync() { } if (next_batch.empty()) { - DoAsyncDone(Status::OK()); + // completes via the round release above + round = std::make_shared(); + round->pending.store(1); return; } - rpcs_.clear(); - controllers_.clear(); - std::unordered_map> region_id_to_region; std::unordered_map> region_id_to_keys; @@ -78,7 +88,12 @@ void TxnCommitTask::DoAsync() { std::shared_ptr tmp; Status s = meta_cache->LookupRegionByKey(key, tmp); if (!s.ok()) { - DoAsyncDone(s); + { + WriteLockGuard guard(rw_lock_); + status_ = s; + } + round = std::make_shared(); + round->pending.store(1); return; } auto iter = region_id_to_region.find(tmp->RegionId()); @@ -88,8 +103,9 @@ void TxnCommitTask::DoAsync() { region_id_to_keys[tmp->RegionId()].push_back(key); } - controllers_.reserve(next_keys_.size()); - rpcs_.reserve(next_keys_.size()); + round = std::make_shared(); + round->controllers.reserve(next_batch.size()); + round->rpcs.reserve(next_batch.size()); for (const auto& entry : region_id_to_keys) { auto region_id = entry.first; auto iter = region_id_to_region.find(region_id); @@ -108,8 +124,8 @@ void TxnCommitTask::DoAsync() { if (rpc->MutableRequest()->keys_size() == FLAGS_txn_max_batch_count) { DINGO_LOG(INFO) << fmt::format("[sdk.txn.{}] commit key, region({}) keys({}) equal max batch count.", txn_impl_->ID(), region->RegionId(), rpc->MutableRequest()->keys_size()); - controllers_.emplace_back(stub, rpc, region); - rpcs_.push_back(rpc); + round->controllers.emplace_back(stub, rpc, region); + round->rpcs.push_back(rpc); // reset rpc rpc = std::make_shared(); @@ -123,21 +139,26 @@ void TxnCommitTask::DoAsync() { *fill = key; } - controllers_.emplace_back(stub, rpc, region); - rpcs_.push_back(rpc); + round->controllers.emplace_back(stub, rpc, region); + round->rpcs.push_back(rpc); } - CHECK(rpcs_.size() == controllers_.size()); + CHECK(round->rpcs.size() == round->controllers.size()); - sub_tasks_count_.store(rpcs_.size()); + // +1 for this issuing frame, released by the scoped cleanup above + round->pending.store(static_cast(round->rpcs.size()) + 1); - for (int i = 0; i < rpcs_.size(); ++i) { - auto& controller = controllers_[i]; - controller.AsyncCall([this, rpc = rpcs_[i].get()](const Status& s) { TxnCommitRpcCallback(s, rpc); }); + for (size_t i = 0; i < round->rpcs.size(); ++i) { + auto& controller = round->controllers[i]; + // round is captured by value: the callbacks collectively keep this + // round's rpcs/controllers alive until every chain fully unwinds + controller.AsyncCall( + [this, round, rpc = round->rpcs[i].get()](const Status& s) { TxnCommitRpcCallback(round, s, rpc); }); } } -void TxnCommitTask::TxnCommitRpcCallback(const Status& status, TxnCommitRpc* rpc) { +void TxnCommitTask::TxnCommitRpcCallback(const std::shared_ptr& round, const Status& status, + TxnCommitRpc* rpc) { DINGO_LOG(DEBUG) << fmt::format("[sdk.txn.{}] rpc: {} request: {} response: {}", txn_impl_->ID(), rpc->Method(), rpc->Request()->ShortDebugString(), rpc->Response()->ShortDebugString()); @@ -176,15 +197,20 @@ void TxnCommitTask::TxnCommitRpcCallback(const Status& status, TxnCommitRpc* rpc } } - if (sub_tasks_count_.fetch_sub(1) == 1) { - Status tmp; - bool tmp_need_retry = false; - { - ReadLockGuard guard(rw_lock_); - tmp = status_; - } - DoAsyncDone(tmp); + FinishSubTask(round); +} + +void TxnCommitTask::FinishSubTask(const std::shared_ptr& round) { + if (round->pending.fetch_sub(1) != 1) { + return; + } + + Status tmp; + { + ReadLockGuard guard(rw_lock_); + tmp = status_; } + DoAsyncDone(tmp); } bool TxnCommitTask::NeedRetry() { diff --git a/src/sdk/transaction/txn_task/txn_commit_task.h b/src/sdk/transaction/txn_task/txn_commit_task.h index fa448c2..df38b5c 100644 --- a/src/sdk/transaction/txn_task/txn_commit_task.h +++ b/src/sdk/transaction/txn_task/txn_commit_task.h @@ -50,7 +50,12 @@ class TxnCommitTask : public TxnTask { std::string Name() const override { return "TxnCommitTask"; } - void TxnCommitRpcCallback(const Status& status, TxnCommitRpc* rpc); + using Round = StoreRpcRound; + + void TxnCommitRpcCallback(const std::shared_ptr& round, const Status& status, TxnCommitRpc* rpc); + + // drops one pending count of the round; the last owner completes the task + void FinishSubTask(const std::shared_ptr& round); Status ProcessTxnCommitResponse(const TxnCommitResponse* response, bool is_primary); @@ -60,11 +65,8 @@ class TxnCommitTask : public TxnTask { bool is_primary_{false}; std::shared_ptr txn_impl_; - std::vector controllers_; - std::vector> rpcs_; std::set next_keys_; - std::atomic sub_tasks_count_{0}; RWLock rw_lock_; Status status_; int64_t retry_count_commit_{0}; diff --git a/src/sdk/transaction/txn_task/txn_prewrite_task.cc b/src/sdk/transaction/txn_task/txn_prewrite_task.cc index 7ecdee6..c6b26b1 100644 --- a/src/sdk/transaction/txn_task/txn_prewrite_task.cc +++ b/src/sdk/transaction/txn_task/txn_prewrite_task.cc @@ -50,6 +50,17 @@ Status TxnPrewriteTask::Init() { } void TxnPrewriteTask::DoAsync() { + // Owns this frame's +1 pending count. Declared before the tracer cleanup so + // it runs after it (reverse destruction order): once released, the last + // finished sub task may complete the task and destroy it, so nothing may + // touch task state afterwards. + std::shared_ptr round; + SCOPED_CLEANUP({ + if (round) { + FinishSubTask(round); + } + }); + auto start_time = TimestampUs(); SCOPED_CLEANUP(txn_impl_->GetTracer()->IncrementPrewriteSdkTime(TimestampUs() - start_time);); @@ -62,13 +73,12 @@ void TxnPrewriteTask::DoAsync() { } if (next_batch.empty()) { - DoAsyncDone(Status::OK()); + // completes via the round release above + round = std::make_shared(); + round->pending.store(1); return; } - rpcs_.clear(); - controllers_.clear(); - std::unordered_map> region_id_to_region; std::unordered_map> region_id_to_mutations; @@ -77,7 +87,13 @@ void TxnPrewriteTask::DoAsync() { std::shared_ptr tmp; Status s = meta_cache->LookupRegionByKey(mutation->key, tmp); if (!s.ok()) { - DoAsyncDone(s); + { + WriteLockGuard guard(rw_lock_); + status_ = s; + need_retry_ = false; + } + round = std::make_shared(); + round->pending.store(1); return; } auto iter = region_id_to_region.find(tmp->RegionId()); @@ -103,7 +119,13 @@ void TxnPrewriteTask::DoAsync() { DINGO_LOG(ERROR) << fmt::format("[sdk.txn.{}] 1pc but region count({}) > 1.", txn_impl_->ID(), region_id_to_region.size()); is_one_pc_ = false; - DoAsyncDone(Status::InvalidArgument("1pc but region count > 1")); + { + WriteLockGuard guard(rw_lock_); + status_ = Status::InvalidArgument("1pc but region count > 1"); + need_retry_ = false; + } + round = std::make_shared(); + round->pending.store(1); return; } } @@ -112,7 +134,13 @@ void TxnPrewriteTask::DoAsync() { Status status = stub.GetTsoProvider()->GenPhysicalTs(2, physical_ts); if (!status.ok()) { - DoAsyncDone(status); + { + WriteLockGuard guard(rw_lock_); + status_ = status; + need_retry_ = false; + } + round = std::make_shared(); + round->pending.store(1); return; } @@ -120,13 +148,20 @@ void TxnPrewriteTask::DoAsync() { if (is_one_pc_ || use_async_commit_) { status = stub.GetTsoProvider()->GenTs(2, commit_ts); if (!status.ok()) { - DoAsyncDone(status); + { + WriteLockGuard guard(rw_lock_); + status_ = status; + need_retry_ = false; + } + round = std::make_shared(); + round->pending.store(1); return; } } - controllers_.reserve(mutations_.size()); - rpcs_.reserve(mutations_.size()); + round = std::make_shared(); + round->controllers.reserve(mutations_.size()); + round->rpcs.reserve(mutations_.size()); for (const auto& entry : region_id_to_mutations) { auto region_id = entry.first; auto iter = region_id_to_region.find(region_id); @@ -159,8 +194,8 @@ void TxnPrewriteTask::DoAsync() { if (rpc->MutableRequest()->mutations_size() == FLAGS_txn_max_batch_count) { DINGO_LOG(INFO) << fmt::format("[sdk.txn.{}] precommit key, region({}) mutations({}) equal max batch count.", txn_impl_->ID(), region->RegionId(), rpc->MutableRequest()->mutations_size()); - controllers_.emplace_back(stub, rpc, region); - rpcs_.push_back(rpc); + round->controllers.emplace_back(stub, rpc, region); + round->rpcs.push_back(rpc); // reset rpc rpc = std::make_shared(); @@ -188,21 +223,26 @@ void TxnPrewriteTask::DoAsync() { TxnMutation2MutationPB(*mutation, rpc->MutableRequest()->add_mutations()); } - controllers_.emplace_back(stub, rpc, region); - rpcs_.push_back(rpc); + round->controllers.emplace_back(stub, rpc, region); + round->rpcs.push_back(rpc); } - CHECK(rpcs_.size() == controllers_.size()); + CHECK(round->rpcs.size() == round->controllers.size()); - sub_tasks_count_.store(rpcs_.size()); + // +1 for this issuing frame, released by the scoped cleanup above + round->pending.store(static_cast(round->rpcs.size()) + 1); - for (int i = 0; i < rpcs_.size(); ++i) { - auto& controller = controllers_[i]; - controller.AsyncCall([this, rpc = rpcs_[i].get()](const Status& s) { TxnPrewriteRpcCallback(s, rpc); }); + for (size_t i = 0; i < round->rpcs.size(); ++i) { + auto& controller = round->controllers[i]; + // round is captured by value: the callbacks collectively keep this + // round's rpcs/controllers alive until every chain fully unwinds + controller.AsyncCall( + [this, round, rpc = round->rpcs[i].get()](const Status& s) { TxnPrewriteRpcCallback(round, s, rpc); }); } } -void TxnPrewriteTask::TxnPrewriteRpcCallback(const Status& status, TxnPrewriteRpc* rpc) { +void TxnPrewriteTask::TxnPrewriteRpcCallback(const std::shared_ptr& round, const Status& status, + TxnPrewriteRpc* rpc) { DINGO_LOG(DEBUG) << fmt::format("[sdk.txn.{}] rpc: {} request: {} response: {}", txn_impl_->ID(), rpc->Method(), rpc->Request()->ShortDebugString(), rpc->Response()->ShortDebugString()); @@ -311,21 +351,27 @@ void TxnPrewriteTask::TxnPrewriteRpcCallback(const Status& status, TxnPrewriteRp txn_impl_->ScheduleHeartBeat(); } - if (sub_tasks_count_.fetch_sub(1) == 1) { - Status tmp; - bool tmp_need_retry = false; - { - ReadLockGuard guard(rw_lock_); - tmp = status_; - tmp_need_retry = need_retry_; - } - if (tmp.ok() && tmp_need_retry) { - txn_impl_->GetTracer()->IncrementPrewriteRetryCount(1); - DoAsyncRetry(); - return; - } - DoAsyncDone(tmp); + FinishSubTask(round); +} + +void TxnPrewriteTask::FinishSubTask(const std::shared_ptr& round) { + if (round->pending.fetch_sub(1) != 1) { + return; + } + + Status tmp; + bool tmp_need_retry = false; + { + ReadLockGuard guard(rw_lock_); + tmp = status_; + tmp_need_retry = need_retry_; + } + if (tmp.ok() && tmp_need_retry) { + txn_impl_->GetTracer()->IncrementPrewriteRetryCount(1); + DoAsyncRetry(); + return; } + DoAsyncDone(tmp); } void TxnPrewriteTask::BackoffAndRetry() { diff --git a/src/sdk/transaction/txn_task/txn_prewrite_task.h b/src/sdk/transaction/txn_task/txn_prewrite_task.h index ba287f6..2a15751 100644 --- a/src/sdk/transaction/txn_task/txn_prewrite_task.h +++ b/src/sdk/transaction/txn_task/txn_prewrite_task.h @@ -55,7 +55,12 @@ class TxnPrewriteTask : public TxnTask { std::string Name() const override { return "TxnPrewriteTask"; } - void TxnPrewriteRpcCallback(const Status& status, TxnPrewriteRpc* rpc); + using Round = StoreRpcRound; + + void TxnPrewriteRpcCallback(const std::shared_ptr& round, const Status& status, TxnPrewriteRpc* rpc); + + // drops one pending count of the round; the last owner decides retry/done + void FinishSubTask(const std::shared_ptr& round); void BackoffAndRetry() override; bool IsRetryError() override; @@ -70,15 +75,12 @@ class TxnPrewriteTask : public TxnTask { const std::map& mutations_ordinarykeys_for_async_commit_; uint64_t& min_commit_ts_; - std::vector controllers_; - std::vector> rpcs_; std::shared_ptr txn_impl_; bool need_retry_{false}; std::map next_mutations_; - std::atomic sub_tasks_count_{0}; RWLock rw_lock_; Status status_; int retry_count_{0}; diff --git a/test/unit_test/sdk/transaction/test_txn_impl.cc b/test/unit_test/sdk/transaction/test_txn_impl.cc index d419ddd..0807999 100644 --- a/test/unit_test/sdk/transaction/test_txn_impl.cc +++ b/test/unit_test/sdk/transaction/test_txn_impl.cc @@ -15,9 +15,15 @@ #include #include +#include +#include #include #include #include +#include +#include +#include +#include #include "dingosdk/client.h" #include "dingosdk/status.h" @@ -327,6 +333,297 @@ TEST_F(SDKTxnImplTest, BatchGetResolveLockFailBackoffRecorded) { FLAGS_txn_op_delay_ms = saved_delay_ms; } +// Completes each mocked SendRpc callback on its own thread, mirroring brpc +// worker-thread completions. +struct AsyncMockRpcCompleter { + std::atomic send_seq{0}; + std::mutex mutex; + std::vector threads; + + void Dispatch(std::function fn) { + std::lock_guard guard(mutex); + threads.emplace_back(std::move(fn)); + } + + void JoinAll() { + int expected = send_seq.load(); + auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5); + while (std::chrono::steady_clock::now() < deadline) { + { + std::lock_guard guard(mutex); + if (static_cast(threads.size()) >= expected) { + break; + } + } + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + std::lock_guard guard(mutex); + for (auto& t : threads) { + if (t.joinable()) { + t.join(); + } + } + } +}; + +// After a successful lock resolve the next round is scheduled with zero delay +// (txn_resolved_lock_retry_delay_ms defaults to 0). That new round must not +// free or mutate per-round state (rpcs/controllers) that the previous round's +// issuing loop still uses, and the task must not complete while an issuing +// DoAsync frame is still on the stack. Run under TSan this catches the +// cross-round races that crash MDS in production (core in Region::IsStale). +TEST_F(SDKTxnImplTest, BatchGetRetryRoundKeepsPreviousRoundAlive) { + const std::vector keys{"b", "d", "f"}; // spans 3 regions -> 3 rpcs per round + const int fanout = static_cast(keys.size()); + constexpr int kConflictRounds = 8; // must stay below FLAGS_txn_op_max_retry + + auto txn = NewTransactionImpl(options); + + auto mock_lock = PrepareLockInfo(); + mock_lock.set_key("b"); + + AsyncMockRpcCompleter completer; + + EXPECT_CALL(*rpc_client, SendRpc).WillRepeatedly([&](Rpc& rpc, std::function cb) { + auto* txn_rpc = dynamic_cast(&rpc); + CHECK_NOTNULL(txn_rpc); + int seq = completer.send_seq.fetch_add(1); + bool conflict = (seq / fanout) < kConflictRounds; + + completer.Dispatch([txn_rpc, conflict, &mock_lock, cb = std::move(cb)] { + if (conflict) { + *txn_rpc->MutableResponse()->mutable_txn_result()->mutable_locked() = mock_lock; + } else { + for (const auto& key : txn_rpc->Request()->keys()) { + auto* kv = txn_rpc->MutableResponse()->add_kvs(); + kv->set_key(key); + kv->set_value(key); + } + } + // rpc, controller and task must stay valid for the whole chain + cb(); + }); + + if (seq % fanout == fanout - 1) { + // stall the issuing loop so the completed round schedules the next + // round while this DoAsync frame is still on the stack + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } + }); + + std::vector kvs; + Status s = txn->BatchGet(keys, kvs); + + completer.JoinAll(); + + EXPECT_TRUE(s.ok()) << s.ToString(); + ASSERT_EQ(kvs.size(), keys.size()); + for (const auto& kv : kvs) { + EXPECT_EQ(kv.key, kv.value); + } + EXPECT_EQ(txn->GetTracer()->ReadRetryCount(), kConflictRounds); +} + +// Callbacks of the same round that take the PushMinCommitTs path record their +// resolved lock ts concurrently; those writes must be synchronized with the +// task lock. Run under TSan this catches the unsynchronized unordered_map +// writes. +TEST_F(SDKTxnImplTest, BatchGetConcurrentPushMinCommitTsCallbacks) { + const std::vector keys{"b", "d", "f"}; + const int fanout = static_cast(keys.size()); + constexpr int kConflictRounds = 4; + + auto txn = NewTransactionImpl(options); + + auto mock_lock = PrepareLockInfo(); + mock_lock.set_key("b"); + + EXPECT_CALL(*txn_lock_resolver, ResolveLock) + .WillRepeatedly(testing::Return(Status::PushMinCommitTs("mock push min_commit_ts"))); + + AsyncMockRpcCompleter completer; + std::atomic arrivals{0}; + + EXPECT_CALL(*rpc_client, SendRpc).WillRepeatedly([&](Rpc& rpc, std::function cb) { + auto* txn_rpc = dynamic_cast(&rpc); + CHECK_NOTNULL(txn_rpc); + int seq = completer.send_seq.fetch_add(1); + bool conflict = (seq / fanout) < kConflictRounds; + + completer.Dispatch([txn_rpc, conflict, fanout, &mock_lock, &arrivals, cb = std::move(cb)] { + if (conflict) { + *txn_rpc->MutableResponse()->mutable_txn_result()->mutable_locked() = mock_lock; + // wait until every callback of this round arrived so the + // PushMinCommitTs bookkeeping runs concurrently + int my = arrivals.fetch_add(1) + 1; + int target = ((my - 1) / fanout + 1) * fanout; + auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(2); + while (arrivals.load() < target && std::chrono::steady_clock::now() < deadline) { + std::this_thread::yield(); + } + } else { + for (const auto& key : txn_rpc->Request()->keys()) { + auto* kv = txn_rpc->MutableResponse()->add_kvs(); + kv->set_key(key); + kv->set_value(key); + } + } + cb(); + }); + }); + + std::vector kvs; + Status s = txn->BatchGet(keys, kvs); + + completer.JoinAll(); + + EXPECT_TRUE(s.ok()) << s.ToString(); + ASSERT_EQ(kvs.size(), keys.size()); + EXPECT_EQ(txn->GetTracer()->ReadRetryCount(), kConflictRounds); +} + +// Same per-round ownership requirement on the prewrite path: a zero-delay +// retry round scheduled after a successful lock resolve must not free state +// the previous round's issuing loop / callback chains still use. +TEST_F(SDKTxnImplTest, PrewriteRetryRoundKeepsPreviousRoundAlive) { + auto txn = NewTransactionImpl(options); + txn->Put("b", "b"); + txn->Put("d", "d"); + txn->Put("f", "f"); + + auto mock_lock = PrepareLockInfo(); + mock_lock.set_key("d"); + + constexpr int kConflictRounds = 8; // must stay below FLAGS_txn_op_max_retry + const int ordinary_fanout = 2; // two non-primary keys, one region each + + EXPECT_CALL(*txn_lock_resolver, ResolveLock).Times(testing::AnyNumber()); + + AsyncMockRpcCompleter completer; + std::atomic ordinary_seq{0}; + + EXPECT_CALL(*rpc_client, SendRpc).WillRepeatedly([&](Rpc& rpc, std::function cb) { + auto* prewrite_rpc = dynamic_cast(&rpc); + if (prewrite_rpc == nullptr) { + // commit / heartbeat rpcs are not under test here + cb(); + return; + } + if (prewrite_rpc->Request()->txn_size() == 1) { + // primary key prewrite succeeds right away + completer.Dispatch([cb = std::move(cb)] { cb(); }); + return; + } + + completer.send_seq.fetch_add(1); + int seq = ordinary_seq.fetch_add(1); + bool conflict = (seq / ordinary_fanout) < kConflictRounds; + + completer.Dispatch([prewrite_rpc, conflict, &mock_lock, cb = std::move(cb)] { + if (conflict) { + auto* txn_result = prewrite_rpc->MutableResponse()->add_txn_result(); + *txn_result->mutable_locked() = mock_lock; + } + cb(); + }); + + if (seq % ordinary_fanout == ordinary_fanout - 1) { + // stall the issuing loop so the completed round schedules the next + // round while this DoAsync frame is still on the stack + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } + }); + + Status s = txn->TEST_PreCommit(); + EXPECT_TRUE(s.ok()) << s.ToString(); + EXPECT_EQ(txn->TEST_IsPreCommittedState(), true); + + completer.JoinAll(); +} + +// A commit round retried after EREGION_VERSION rebuilds per-round state; that +// new round must not free or mutate state the previous round's issuing frame +// (stalled across the retry backoff) still reads. The backoff is zeroed so +// the retry goes through Actuator::Execute: the Timer path confuses TSan's +// happens-before tracking (see tsan_suppressions.txt). +TEST_F(SDKTxnImplTest, CommitRetryRoundKeepsPreviousRoundAlive) { + int64_t saved_delay_ms = FLAGS_txn_op_delay_ms; + FLAGS_txn_op_delay_ms = 0; + + auto txn = NewTransactionImpl(options); + txn->Put("b", "b"); + txn->Put("d", "d"); + txn->Put("f", "f"); + + const std::string pk = txn->TEST_GetPrimaryKey(); + // keys b/d/f live in regions [a,c) [c,e) [e,g): region id is pk[0] - 1 + const char pk_char = pk[0]; + + AsyncMockRpcCompleter completer; + std::atomic primary_commit_seq{0}; + + EXPECT_CALL(*rpc_client, SendRpc).WillRepeatedly([&](Rpc& rpc, std::function cb) { + auto* commit_rpc = dynamic_cast(&rpc); + if (commit_rpc == nullptr) { + // prewrite / heartbeat rpcs complete inline + cb(); + return; + } + if (!(commit_rpc->Request()->keys_size() == 1 && commit_rpc->Request()->keys(0) == pk)) { + // ordinary key commits are not under test here + cb(); + return; + } + + completer.send_seq.fetch_add(1); + int seq = primary_commit_seq.fetch_add(1); + constexpr int kErrorRounds = 6; // must stay below FLAGS_txn_op_max_retry + if (seq < kErrorRounds) { + // region version mismatch; store_region_info (with a growing epoch) + // refreshes the meta cache so every retry round can route again + completer.Dispatch([commit_rpc, pk_char, seq, cb = std::move(cb)] { + auto* error = commit_rpc->MutableResponse()->mutable_error(); + error->set_errcode(pb::error::EREGION_VERSION); + auto* info = error->mutable_store_region_info(); + info->set_region_id(pk_char - 1); + info->mutable_current_region_epoch()->set_version(2 + seq); + info->mutable_current_region_epoch()->set_conf_version(1); + info->mutable_current_range()->set_start_key(std::string(1, pk_char - 1)); + info->mutable_current_range()->set_end_key(std::string(1, pk_char + 1)); + for (const auto& entry : kInitReplica) { + auto* peer = info->add_peers(); + peer->mutable_server_location()->set_host(entry.first.Host()); + peer->mutable_server_location()->set_port(entry.first.Port()); + } + cb(); + }); + // stall this issuing frame across the zero-delay retry so the next + // round runs while this frame still reads this round's state + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + return; + } + completer.Dispatch([cb = std::move(cb)] { cb(); }); + }); + + Status s = txn->TEST_PreCommit(); + EXPECT_TRUE(s.ok()) << s.ToString(); + + s = txn->TEST_Commit(); + EXPECT_TRUE(s.ok()) << s.ToString(); + + int poll = 0; + while (!txn->TEST_IsFinishedState()) { + CHECK(poll++ < 3000); + usleep(1000); + } + + completer.JoinAll(); + // let stalled frames leave the mock before test locals die + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + + FLAGS_txn_op_delay_ms = saved_delay_ms; +} + TEST_F(SDKTxnImplTest, BatchGetRetryBackoffEscalates) { int64_t saved_delay_ms = FLAGS_txn_op_delay_ms; FLAGS_txn_op_delay_ms = 5; diff --git a/test/unit_test/sdk/tsan_suppressions.txt b/test/unit_test/sdk/tsan_suppressions.txt new file mode 100644 index 0000000..60dcf00 --- /dev/null +++ b/test/unit_test/sdk/tsan_suppressions.txt @@ -0,0 +1,18 @@ +# ThreadSanitizer suppressions for sdk_unit_test. +# +# The dingo-eureka third-party libraries (protobuf, brpc, ...) are prebuilt +# without TSan instrumentation, so their internal synchronization is invisible +# to TSan. Keep entries narrow: suppress only known-safe internal lazy-init +# paths, never whole libraries, so real races on message objects still show. + +# protobuf descriptor lazy initialization is guarded by an internal call_once +# TSan cannot see. +race:google::protobuf::*OnceInit* +race:google::protobuf::DescriptorPool::Tables::AllocateBytes + +# Pre-existing Timer reports in the std::thread actuator (double lock in +# Timer::Add vs Run/Stop plus races on FunctionInfo). They reproduce on a +# pristine tree and are tracked separately; suppressed here so they do not +# mask task-level reports. Remove once the Timer is fixed. +mutex:dingodb::sdk::Timer::* +race:dingodb::sdk::Timer::*