From 494ca04dced317c36232496b56a121a0477e9501 Mon Sep 17 00:00:00 2001 From: Zihui Deng <451809218@qq.com> Date: Mon, 3 Aug 2026 16:22:30 +0800 Subject: [PATCH] [fix][sdk] Serialize TSO refills and reuse cached batches Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/sdk/common/param_config.cc | 4 + src/sdk/transaction/tso.cc | 110 +++++++++------- src/sdk/transaction/tso.h | 15 ++- test/unit_test/sdk/transaction/test_tso.cc | 146 +++++++++++++++++++++ 4 files changed, 225 insertions(+), 50 deletions(-) create mode 100644 test/unit_test/sdk/transaction/test_tso.cc diff --git a/src/sdk/common/param_config.cc b/src/sdk/common/param_config.cc index bb69592..1c0c97f 100644 --- a/src/sdk/common/param_config.cc +++ b/src/sdk/common/param_config.cc @@ -77,6 +77,10 @@ DEFINE_int64(txn_heartbeat_lock_delay_ms, 20000, "txn heartbeat lock delay time" DEFINE_int64(txn_check_status_interval_ms, 5, "txn check status interval ms"); DEFINE_uint32(stale_period_us, 1000, "stale period us default 1000 us, used for tso provider"); +// a validator is what makes the flag reloadable through brpc's /flags handler, +// this one is the main tso tuning knob so it must be changeable at runtime +static bool ValidateStalePeriodUs(const char*, uint32_t) { return true; } +DEFINE_validator(stale_period_us, &ValidateStalePeriodUs); DEFINE_uint32(tso_batch_size, 256, "tso batch size default 256, used for tso provider"); DEFINE_uint32(tso_anchor_max_age_us, 60000000, "max age of the physical-time anchor before GetPhysicalTs falls back to a real tso fetch"); diff --git a/src/sdk/transaction/tso.cc b/src/sdk/transaction/tso.cc index 6b70be9..8280bb0 100644 --- a/src/sdk/transaction/tso.cc +++ b/src/sdk/transaction/tso.cc @@ -14,14 +14,14 @@ #include "sdk/transaction/tso.h" +#include + #include "dingosdk/status.h" #include "fmt/format.h" #include "sdk/client_stub.h" #include "sdk/common/common.h" #include "sdk/common/helper.h" #include "sdk/common/param_config.h" -#include "sdk/rpc/coordinator_rpc.h" -#include "sdk/utils/async_util.h" #include "sdk/utils/rw_lock.h" namespace dingodb { @@ -31,27 +31,38 @@ TsoProvider::TsoProvider(const ClientStub& stub) : stub_(stub), batch_size_(FLAG last_time_us_ = TimestampUs(); } +// caller must hold the write lock +bool TsoProvider::TryAllocate(uint32_t count, int64_t& ts, bool check_stale) { + if ((check_stale && IsStale()) || max_logical_ < count + next_logical_) return false; + + TsoTimestamp tso; + tso.set_physical(physical_); + tso.set_logical(next_logical_); + ts = Tso2Timestamp(tso); + + next_logical_ += count; + CHECK(ts > 0) << "ts should be greater than 0 , ts:" << ts; + + return true; +} + Status TsoProvider::GenTs(uint32_t count, int64_t& ts) { - // lock - WriteLockGuard guard(rwlock_); - int retry = 0; Status status; - bool is_stale = IsStale(); - do { - if (max_logical_ >= count + next_logical_ && !is_stale) { - TsoTimestamp tso; - tso.set_physical(physical_); - tso.set_logical(next_logical_); - ts = Tso2Timestamp(tso); - - next_logical_ += count; - CHECK(ts > 0) << "ts should be greater than 0 , ts:" << ts; - return Status::OK(); + int retry = 0; + bool check_stale = true; + do { + { + WriteLockGuard guard(rwlock_); + if (TryAllocate(count, ts, check_stale)) return Status::OK(); } - status = FetchTso(batch_size_); - is_stale = false; + // the coordinator round trip runs outside rwlock_, so callers that can + // still serve from the cached batch are not blocked behind it + status = RefillBatch(count); + // a refill just happened, ours or a concurrent one: take what it produced + // instead of re-testing the clock, otherwise a tiny stale window starves + check_stale = false; } while (retry++ < FLAGS_txn_op_max_retry); @@ -69,24 +80,25 @@ Status TsoProvider::GenTs(uint32_t count, int64_t& ts) { } Status TsoProvider::GenPhysicalTs(int32_t count, int64_t& physical_ts) { - // lock - WriteLockGuard guard(rwlock_); - // for txn heartbeat, we need to re-acquire physical ts - Refresh(); + Status status; int retry = 0; - Status status; do { - status = FetchTso(batch_size_); + // txn heartbeat needs a current physical time, so always go through a + // refill; a batch another caller just installed is equally fresh + status = RefillBatch(count); - if (max_logical_ >= count + next_logical_) { - physical_ts = physical_; + if (status.ok()) { + WriteLockGuard guard(rwlock_); + if (max_logical_ >= count + next_logical_) { + physical_ts = physical_; - next_logical_ += count; + next_logical_ += count; - CHECK(physical_ts > 0) << "physical_ts should be greater than 0 , physical_ts:" << physical_ts; + CHECK(physical_ts > 0) << "physical_ts should be greater than 0 , physical_ts:" << physical_ts; - return Status::OK(); + return Status::OK(); + } } } while (retry++ < FLAGS_txn_op_max_retry); @@ -115,7 +127,7 @@ Status TsoProvider::GetPhysicalTs(int64_t& physical_ts) { if (anchor_physical_ms_ > 0) { int64_t age_us = SteadyUs() - anchor_steady_us_; if (age_us >= 0 && age_us < FLAGS_tso_anchor_max_age_us) { - int64_t est = anchor_physical_ms_ + age_us / 1000; + int64_t est = anchor_physical_ms_ + (age_us / 1000); int64_t prev = max_physical_ms_.load(std::memory_order_relaxed); while (est > prev && !max_physical_ms_.compare_exchange_weak(prev, est)) { } @@ -129,19 +141,18 @@ Status TsoProvider::GetPhysicalTs(int64_t& physical_ts) { return GenPhysicalTs(2, physical_ts); } -void TsoProvider::Refresh() { - last_time_us_ = TimestampUs(); - physical_ = 0; - next_logical_ = 0; - max_logical_ = 0; -} +bool TsoProvider::IsStale() const { return TimestampUs() > (last_time_us_ + FLAGS_stale_period_us); } -bool TsoProvider::IsStale() { - auto now_us = TimestampUs(); - bool is_stale = now_us > (last_time_us_ + FLAGS_stale_period_us); - if (is_stale) last_time_us_ = now_us; +Status TsoProvider::RefillBatch(uint32_t count) { + std::lock_guard guard(fetch_mutex_); - return is_stale; + { + // somebody refilled while we waited for the mutex, reuse their batch + ReadLockGuard read_guard(rwlock_); + if (!IsStale() && max_logical_ >= count + next_logical_) return Status::OK(); + } + + return FetchTso(batch_size_); } Status TsoProvider::FetchTso(uint32_t count) { @@ -159,12 +170,19 @@ Status TsoProvider::FetchTso(uint32_t count) { const auto& tso = rpc.Response()->start_timestamp(); const auto& ts_count = rpc.Response()->count(); - physical_ = tso.physical(); - next_logical_ = tso.logical(); - max_logical_ = next_logical_ + ts_count - 1; - anchor_physical_ms_ = tso.physical(); - anchor_steady_us_ = SteadyUs(); + { + WriteLockGuard guard(rwlock_); + physical_ = tso.physical(); + next_logical_ = tso.logical(); + max_logical_ = next_logical_ + ts_count - 1; + // freshness is measured from the fetch itself, not from the last time + // somebody noticed the batch had gone stale + last_time_us_ = TimestampUs(); + + anchor_physical_ms_ = tso.physical(); + anchor_steady_us_ = SteadyUs(); + } DINGO_LOG(DEBUG) << fmt::format("[sdk.tso] fetch tso ts({}) count({}).", Tso2Timestamp(tso), ts_count); diff --git a/src/sdk/transaction/tso.h b/src/sdk/transaction/tso.h index fc15286..661ea54 100644 --- a/src/sdk/transaction/tso.h +++ b/src/sdk/transaction/tso.h @@ -19,6 +19,7 @@ #include #include +#include "bthread/mutex.h" #include "dingosdk/status.h" #include "proto/meta.pb.h" #include "sdk/utils/rw_lock.h" @@ -46,11 +47,13 @@ class TsoProvider { // than FLAGS_tso_anchor_max_age_us. Status GetPhysicalTs(int64_t& physical_ts); - void Refresh(); - private: - // when period is beyond 1ms is considered stale - bool IsStale(); + // batch is only usable for FLAGS_stale_period_us after it was fetched + bool IsStale() const; + // allocates from the cached batch, caller must hold the write lock + bool TryAllocate(uint32_t count, int64_t& ts, bool check_stale); + // fetches a new batch, must NOT be called with rwlock_ held + Status RefillBatch(uint32_t count); Status FetchTso(uint32_t count); const ClientStub& stub_; @@ -60,6 +63,10 @@ class TsoProvider { RWLock rwlock_; + // serializes fetchers so that concurrent callers share a single coordinator + // round trip instead of each issuing one; never held together with rwlock_ + bthread::Mutex fetch_mutex_; + int64_t physical_{0}; int64_t next_logical_{0}; int64_t max_logical_{0}; diff --git a/test/unit_test/sdk/transaction/test_tso.cc b/test/unit_test/sdk/transaction/test_tso.cc new file mode 100644 index 0000000..35f1717 --- /dev/null +++ b/test/unit_test/sdk/transaction/test_tso.cc @@ -0,0 +1,146 @@ +// Copyright (c) 2026 dingodb.com, Inc. All Rights Reserved +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include +#include +#include +#include +#include +#include + +#include "gmock/gmock.h" +#include "gtest/gtest.h" +#include "sdk/common/param_config.h" +#include "sdk/rpc/coordinator_rpc.h" +#include "sdk/transaction/tso.h" +#include "test_base.h" + +namespace dingodb { +namespace sdk { + +class TsoProviderTest : public TestBase { + protected: + void SetUp() override { + fetch_count_.store(0); + next_physical_.store(1); + + ON_CALL(*tso_rpc_controller, SyncCall).WillByDefault([this](Rpc& rpc) { + auto& tso_rpc = dynamic_cast(rpc); + const uint32_t count = tso_rpc.Request()->count(); + + fetch_count_.fetch_add(1); + std::this_thread::sleep_for(std::chrono::microseconds(fetch_delay_us_.load())); + + auto* start = tso_rpc.MutableResponse()->mutable_start_timestamp(); + start->set_physical(next_physical_.fetch_add(1)); + start->set_logical(0); + tso_rpc.MutableResponse()->set_count(count); + + return Status::OK(); + }); + } + + std::atomic fetch_count_{0}; + std::atomic next_physical_{1}; + // a real coordinator round trip is ~100us; tests widen it to make blocking + // behaviour observable + std::atomic fetch_delay_us_{500}; +}; + +// Timestamps must be unique and strictly increasing, and concurrent callers +// that need a refill must share one coordinator round trip instead of each +// issuing their own. +TEST_F(TsoProviderTest, ConcurrentGenTsSharesOneFetch) { + constexpr int kThreadNum = 32; + constexpr int kPerThread = 50; + + // window shorter than the workload, so refills happen while callers are + // running: without single flight each of them would issue its own rpc + FLAGS_stale_period_us = 2000; + + std::vector> results(kThreadNum); + std::vector threads; + threads.reserve(kThreadNum); + for (int i = 0; i < kThreadNum; i++) { + threads.emplace_back([&, i]() { + for (int j = 0; j < kPerThread; j++) { + int64_t ts = 0; + ASSERT_TRUE(tso_provider->GenTs(2, ts).ok()); + results[i].push_back(ts); + } + }); + } + for (auto& thread : threads) thread.join(); + + std::set all; + for (const auto& per_thread : results) { + for (size_t j = 1; j < per_thread.size(); j++) { + EXPECT_GT(per_thread[j], per_thread[j - 1]) << "ts must increase within a caller"; + } + all.insert(per_thread.begin(), per_thread.end()); + } + EXPECT_EQ(all.size(), static_cast(kThreadNum * kPerThread)) << "duplicate ts handed out"; + + std::cout << "fetches=" << fetch_count_.load() << " allocations=" << kThreadNum * kPerThread << std::endl; + // concurrent callers must share a round trip instead of each doing one + EXPECT_LT(fetch_count_.load(), static_cast(kThreadNum * kPerThread) / 10); +} + +// With a sane staleness window the batch is actually consumed, so the number +// of round trips is driven by batch exhaustion, not by the clock. +TEST_F(TsoProviderTest, FreshBatchIsReusedAcrossCalls) { + FLAGS_stale_period_us = 1000000; + + const int64_t op_num = 100; // well inside one batch of FLAGS_tso_batch_size logical numbers + for (int64_t i = 0; i < op_num; i++) { + int64_t ts = 0; + ASSERT_TRUE(tso_provider->GenTs(2, ts).ok()); + } + + EXPECT_EQ(fetch_count_.load(), 1) << "one batch must cover " << op_num << " allocations"; +} + +// The physical-time fast path only reads the anchor, so it must not queue +// behind an in-flight coordinator round trip started by another caller. +TEST_F(TsoProviderTest, PhysicalTsNotBlockedByInFlightFetch) { + FLAGS_stale_period_us = 1000; + + // prime the anchor with a quick fetch + int64_t ts = 0; + ASSERT_TRUE(tso_provider->GenTs(2, ts).ok()); + + fetch_delay_us_.store(300000); // 300ms round trip + std::this_thread::sleep_for(std::chrono::milliseconds(5)); // batch goes stale + + std::thread fetcher([&]() { + int64_t slow_ts = 0; + EXPECT_TRUE(tso_provider->GenTs(2, slow_ts).ok()); + }); + + std::this_thread::sleep_for(std::chrono::milliseconds(20)); // let the rpc start + + auto start = std::chrono::steady_clock::now(); + int64_t physical_ts = 0; + ASSERT_TRUE(tso_provider->GetPhysicalTs(physical_ts).ok()); + const auto elapsed_ms = + std::chrono::duration_cast(std::chrono::steady_clock::now() - start).count(); + + fetcher.join(); + + std::cout << "GetPhysicalTs elapsed=" << elapsed_ms << "ms (fetch takes 300ms)" << std::endl; + EXPECT_LT(elapsed_ms, 100) << "physical ts blocked behind the fetch rpc"; +} + +} // namespace sdk +} // namespace dingodb