diff --git a/packages/feedsim/third_party/src/workloads/ranking/LeafNodeRank.cc b/packages/feedsim/third_party/src/workloads/ranking/LeafNodeRank.cc index 1f175ba61..e96ae57cd 100644 --- a/packages/feedsim/third_party/src/workloads/ranking/LeafNodeRank.cc +++ b/packages/feedsim/third_party/src/workloads/ranking/LeafNodeRank.cc @@ -201,15 +201,6 @@ struct ThreadData { // --rpc_dist_path is set; empty otherwise (in which case the legacy // folly::futures::sleep path is used). // - // mock_clients holds one MockServicesClient per SREventBase in the - // pool; each MockServiceAsyncClient is pinned to one folly::EventBase - // (see MockServicesClient.h), so to fan an outbound RPC across all - // EBs we need one client per EB. issueOutboundFanout round-robins - // across these via next_mock_client_idx. This addresses the - // single-channel serialization where the prior single-client-per- - // dispatcher design funneled all outbound RPCs through one Rocket - // channel on one EB, producing dispatch_per_rpc ≫ mock_handler_actual - // even with folly::window(K=16) bounding per-fanout concurrency. // registry and silesia are shared (read-only after load) — held here // as raw pointers to globals to avoid shared_ptr churn on the // request path. @@ -2520,6 +2511,7 @@ int main(int argc, char** argv) { g_fanout_total_us.dump("fanout_total"); g_dispatch_us.dump("dispatch_per_rpc"); g_sampled_lat_us.dump("sampled_latency_us"); + ranking::MockServicesClient::dumpKeepaliveCounters(); } }); debug_dump_thread.detach(); diff --git a/packages/feedsim/third_party/src/workloads/ranking/MockClientPolicy.h b/packages/feedsim/third_party/src/workloads/ranking/MockClientPolicy.h new file mode 100644 index 000000000..28e278e63 --- /dev/null +++ b/packages/feedsim/third_party/src/workloads/ranking/MockClientPolicy.h @@ -0,0 +1,81 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. +// +// This source code is licensed under the MIT license found in the +// LICENSE file in the root directory of this source tree. + +#pragma once + +#include +#include +#include +#include +#include + +#include + +namespace ranking { + +class IdleKeepalivePolicy { + public: + using Clock = std::chrono::steady_clock; + enum class Reason { Idle, RecentActivity, RealRequest, KeepalivePending }; + struct Decision { + bool send; + std::chrono::milliseconds delay; + Reason reason; + }; + + IdleKeepalivePolicy( + std::chrono::milliseconds interval, Clock::time_point now) + : interval_(interval), state_(State{now}) {} + + void requestStarted(Clock::time_point now) { + auto state = state_.lock(); + ++state->requestsInFlight; + state->lastActivity = std::max(state->lastActivity, now); + } + + void requestFinished(Clock::time_point now) { + auto state = state_.lock(); + assert(state->requestsInFlight > 0); + --state->requestsInFlight; + state->lastActivity = std::max(state->lastActivity, now); + } + + void keepaliveFinished(Clock::time_point now) { + auto state = state_.lock(); + state->keepaliveInFlight = false; + state->lastActivity = std::max(state->lastActivity, now); + } + + Decision onTimer(Clock::time_point now) { + auto state = state_.lock(); + if (state->requestsInFlight > 0) { + return {false, interval_, Reason::RealRequest}; + } + if (state->keepaliveInFlight) { + return {false, interval_, Reason::KeepalivePending}; + } + const auto deadline = state->lastActivity + interval_; + if (now < deadline) { + return { + false, + std::chrono::ceil(deadline - now), + Reason::RecentActivity}; + } + state->keepaliveInFlight = true; + return {true, interval_, Reason::Idle}; + } + + private: + struct State { + Clock::time_point lastActivity; + size_t requestsInFlight{0}; + bool keepaliveInFlight{false}; + }; + + const std::chrono::milliseconds interval_; + folly::Synchronized state_; +}; + +} // namespace ranking diff --git a/packages/feedsim/third_party/src/workloads/ranking/MockServicesClient.cc b/packages/feedsim/third_party/src/workloads/ranking/MockServicesClient.cc index 5c673e863..7bfb23d2b 100644 --- a/packages/feedsim/third_party/src/workloads/ranking/MockServicesClient.cc +++ b/packages/feedsim/third_party/src/workloads/ranking/MockServicesClient.cc @@ -15,6 +15,8 @@ #include "MockServicesClient.h" #include +#include +#include #include #include #include @@ -27,6 +29,7 @@ #include #include +#include #include #include @@ -107,25 +110,27 @@ double resolveZstdFraction() { // monotonic index. The index modulo 100 vs (frac * 100) gives a deterministic // per-instance decision: e.g. frac=0.5 -> every other client gets ZSTD. std::atomic g_mock_client_idx{0}; + +struct alignas(64) MockClientCounters { + std::atomic real_rpcs{0}; + std::atomic keepalives{0}; + std::atomic recent_activity{0}; + std::atomic real_in_flight{0}; + std::atomic keepalive_in_flight{0}; +}; + +std::array g_mock_client_counters; + +MockClientCounters& countersFor(folly::EventBase* evb) { + const auto address = reinterpret_cast(evb); + return g_mock_client_counters[ + ((address >> 6) ^ (address >> 18)) % g_mock_client_counters.size()]; +} } // namespace namespace ranking { -// KeepaliveTimer fires a fire-and-forget getStatus() RPC every -// keepalive_interval_ms to keep the underlying Rocket channel warm. -// -// Why this exists: each leaf thread owns one MockServicesClient per -// SREventBase. At low QPS most channels see no traffic for hundreds of ms -// between request bursts, then pay re-arm + deep C-state wake costs on the -// next RPC. Per-channel keepalive defeats this by ensuring every channel -// sees traffic at least every keepalive_interval_ms. -// -// Thread-affinity: scheduled on the same EventBase as the parent -// MockServicesClient, so the callback runs on the right thread to call -// dispatchByEnum() (which is thread-affine). Drops the resulting -// SemiFuture immediately (fire-and-forget); transport errors are -// swallowed silently — keepalive failures should not propagate to the -// application path. +// Runs getStatus probes on the client EventBase. class MockServicesClient::KeepaliveTimer : public folly::AsyncTimeout { public: KeepaliveTimer( @@ -141,24 +146,43 @@ class MockServicesClient::KeepaliveTimer : public folly::AsyncTimeout { } void timeoutExpired() noexcept override { - // Reschedule first so we don't drop the next tick if dispatch throws. - scheduleTimeout(interval_); + const auto policy = parent_->idle_keepalive_policy_; + const auto decision = policy->onTimer(IdleKeepalivePolicy::Clock::now()); + scheduleTimeout(decision.delay); + if (!decision.send) { + auto& counters = countersFor(parent_->evb_); + switch (decision.reason) { + case IdleKeepalivePolicy::Reason::RecentActivity: + counters.recent_activity.fetch_add(1, std::memory_order_relaxed); + break; + case IdleKeepalivePolicy::Reason::RealRequest: + counters.real_in_flight.fetch_add(1, std::memory_order_relaxed); + break; + case IdleKeepalivePolicy::Reason::KeepalivePending: + counters.keepalive_in_flight.fetch_add(1, std::memory_order_relaxed); + break; + case IdleKeepalivePolicy::Reason::Idle: + break; + } + return; + } - // Fire-and-forget getStatus() with latency_us=0 (lightest possible - // server-side handler). The 4-byte response header is the wire- - // contract minimum. We don't await — the returned SemiFuture goes - // out of scope but the underlying RPC remains in flight on the - // channel until completion, achieving the warming effect. try { std::string probe(4, '\0'); writeBigEndianResponseSize(probe.data(), 4); + countersFor(parent_->evb_).keepalives.fetch_add( + 1, std::memory_order_relaxed); parent_->client_->semifuture_getStatus(probe, /*latency_us=*/0) + .deferEnsure([policy]() { + policy->keepaliveFinished(IdleKeepalivePolicy::Clock::now()); + }) .via(parent_->evb_) .thenValue([](std::string&&) {}) .thenError(folly::tag_t{}, [](const std::exception&) { // Swallow transport errors silently. The next iter will retry. }); } catch (...) { + policy->keepaliveFinished(IdleKeepalivePolicy::Clock::now()); // Defensive — never let the timer callback propagate. } } @@ -174,7 +198,11 @@ MockServicesClient::MockServicesClient( uint16_t port, std::chrono::milliseconds keepalive_interval, const MockServicesConnectionOptions& connection_options) - : evb_(evb) { + : evb_(evb), + idle_keepalive_policy_(keepalive_interval.count() > 0 + ? std::make_shared( + keepalive_interval, IdleKeepalivePolicy::Clock::now()) + : nullptr) { if (evb_ == nullptr) { throw std::invalid_argument( "MockServicesClient: EventBase must not be null"); @@ -373,6 +401,27 @@ folly::SemiFuture MockServicesClient::dispatchByEnum( MethodIdx idx, const std::string& request, int32_t latency_us) { + countersFor(evb_).real_rpcs.fetch_add(1, std::memory_order_relaxed); + auto policy = idle_keepalive_policy_; + if (!policy) { + return dispatchByEnumImpl(idx, request, latency_us); + } + policy->requestStarted(IdleKeepalivePolicy::Clock::now()); + try { + return dispatchByEnumImpl(idx, request, latency_us) + .deferEnsure([policy]() { + policy->requestFinished(IdleKeepalivePolicy::Clock::now()); + }); + } catch (...) { + policy->requestFinished(IdleKeepalivePolicy::Clock::now()); + throw; + } +} + +folly::SemiFuture MockServicesClient::dispatchByEnumImpl( + MethodIdx idx, + const std::string& request, + int32_t latency_us) { // Compile-time switch over MethodIdx. Each case calls the named // generated semifuture_() so Strobelight sees distinct // AsyncClient::send_ symbols — the whole reason we declared @@ -429,4 +478,28 @@ folly::SemiFuture MockServicesClient::dispatchByEnum( std::runtime_error("MockServicesClient::dispatchByEnum: invalid idx")); } +void MockServicesClient::dumpKeepaliveCounters() { + uint64_t real = 0; + uint64_t pings = 0; + uint64_t recent = 0; + uint64_t busy = 0; + uint64_t pending = 0; + for (const auto& counters : g_mock_client_counters) { + real += counters.real_rpcs.load(std::memory_order_relaxed); + pings += counters.keepalives.load(std::memory_order_relaxed); + recent += counters.recent_activity.load(std::memory_order_relaxed); + busy += counters.real_in_flight.load(std::memory_order_relaxed); + pending += counters.keepalive_in_flight.load(std::memory_order_relaxed); + } + const auto timestamp = std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()).count(); + std::ostringstream line; + line << "[mock_client_counters] timestamp_ms=" << timestamp + << " pid=" << getpid() << " real_rpcs=" << real + << " keepalives=" << pings << " postponed_recent=" << recent + << " skipped_busy=" << busy << " skipped_pending_ping=" << pending + << "\n"; + std::cerr << line.str(); +} + } // namespace ranking diff --git a/packages/feedsim/third_party/src/workloads/ranking/MockServicesClient.h b/packages/feedsim/third_party/src/workloads/ranking/MockServicesClient.h index b02158a28..ee6d9202a 100644 --- a/packages/feedsim/third_party/src/workloads/ranking/MockServicesClient.h +++ b/packages/feedsim/third_party/src/workloads/ranking/MockServicesClient.h @@ -25,6 +25,7 @@ #include #include "RpcDistRegistry.h" +#include "MockClientPolicy.h" // The generated cpp2 client is exposed as a `using` alias // (`mock_services::MockServiceAsyncClient = apache::thrift::Client<...>`), @@ -45,9 +46,8 @@ struct MockServicesConnectionOptions { /** * MockServicesClient — per-thread wrapper around the generated - * MockServiceAsyncClient. Each LeafNodeRank worker thread owns one - * instance, pinned to its own folly::EventBase (typically a thread from - * the SREventBase pool — matches the production EventBase placement). + * MockServiceAsyncClient. Each LeafNodeRank worker owns a set of clients, + * each pinned to an EventBase from the shared SREventBase pool. * * Thread-safety: NOT thread-safe. Each instance is tied to one EventBase * and must only be used from that EventBase's thread (or via futures @@ -107,16 +107,18 @@ class MockServicesClient { return evb_; } + static void dumpKeepaliveCounters(); + private: - // KeepaliveTimer (defined in .cc) fires a fire-and-forget getStatus() - // probe RPC every keepalive_interval_ms to keep the underlying Rocket - // channel + SREventBase warm. Forward declared here so the unique_ptr - // member doesn't pull AsyncTimeout into the header's public surface. class KeepaliveTimer; + folly::SemiFuture dispatchByEnumImpl( + MethodIdx idx, const std::string& request, int32_t latency_us); + folly::EventBase* evb_; std::unique_ptr client_; std::unique_ptr keepalive_; + std::shared_ptr idle_keepalive_policy_; }; /** diff --git a/packages/feedsim/third_party/src/workloads/ranking/mock_services/MockClientPolicyTest.cpp b/packages/feedsim/third_party/src/workloads/ranking/mock_services/MockClientPolicyTest.cpp new file mode 100644 index 000000000..8961d932a --- /dev/null +++ b/packages/feedsim/third_party/src/workloads/ranking/mock_services/MockClientPolicyTest.cpp @@ -0,0 +1,73 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. +// +// This source code is licensed under the MIT license found in the +// LICENSE file in the root directory of this source tree. + +#include + +#include + +#include "MockClientPolicy.h" + +namespace ranking { +namespace { + +using namespace std::chrono_literals; +using Clock = IdleKeepalivePolicy::Clock; + +TEST(IdleKeepalive, WaitsForInitialIdleDeadline) { + const Clock::time_point start{}; + IdleKeepalivePolicy policy(200ms, start); + auto decision = policy.onTimer(start + 199ms); + EXPECT_FALSE(decision.send); + EXPECT_EQ(decision.delay, 1ms); + EXPECT_TRUE(policy.onTimer(start + 200ms).send); +} + +TEST(IdleKeepalive, SuppressesWhileAnyRealRequestIsOutstanding) { + const Clock::time_point start{}; + IdleKeepalivePolicy policy(200ms, start); + policy.requestStarted(start + 10ms); + policy.requestStarted(start + 20ms); + policy.requestFinished(start + 30ms); + EXPECT_FALSE(policy.onTimer(start + 2s).send); + policy.requestFinished(start + 3s); + EXPECT_FALSE(policy.onTimer(start + 3199ms).send); + EXPECT_TRUE(policy.onTimer(start + 3200ms).send); +} + +TEST(IdleKeepalive, RecentCompletionPostponesAnAlreadyArmedTimer) { + const Clock::time_point start{}; + IdleKeepalivePolicy policy(200ms, start); + policy.requestStarted(start + 150ms); + policy.requestFinished(start + 190ms); + auto decision = policy.onTimer(start + 200ms); + EXPECT_FALSE(decision.send); + EXPECT_EQ(decision.delay, 190ms); + EXPECT_TRUE(policy.onTimer(start + 390ms).send); +} + +TEST(IdleKeepalive, AllowsOnlyOneKeepaliveUntilItsCompletion) { + const Clock::time_point start{}; + IdleKeepalivePolicy policy(200ms, start); + EXPECT_TRUE(policy.onTimer(start + 200ms).send); + EXPECT_FALSE(policy.onTimer(start + 1s).send); + policy.keepaliveFinished(start + 1100ms); + EXPECT_FALSE(policy.onTimer(start + 1299ms).send); + EXPECT_TRUE(policy.onTimer(start + 1300ms).send); +} + +TEST(IdleKeepalive, LateBookkeepingCannotMoveActivityBackwards) { + const Clock::time_point start{}; + IdleKeepalivePolicy policy(200ms, start); + policy.requestStarted(start + 190ms); + policy.requestStarted(start + 180ms); + policy.requestFinished(start + 195ms); + policy.requestFinished(start + 185ms); + auto decision = policy.onTimer(start + 200ms); + EXPECT_FALSE(decision.send); + EXPECT_EQ(decision.delay, 195ms); +} + +} // namespace +} // namespace ranking