Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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();
Expand Down
Original file line number Diff line number Diff line change
@@ -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 <algorithm>
#include <cassert>
#include <chrono>
#include <cstddef>
#include <mutex>

#include <folly/Synchronized.h>

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<std::chrono::milliseconds>(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, std::mutex> state_;
};

} // namespace ranking
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
#include "MockServicesClient.h"

#include <algorithm>
#include <array>
#include <atomic>
#include <chrono>
#include <exception>
#include <iostream>
Expand All @@ -27,6 +29,7 @@

#include <cstdlib>
#include <cstring>
#include <unistd.h>

#include <folly/SocketAddress.h>
#include <folly/io/async/AsyncSSLSocket.h>
Expand Down Expand Up @@ -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<std::size_t> g_mock_client_idx{0};

struct alignas(64) MockClientCounters {
std::atomic<uint64_t> real_rpcs{0};
std::atomic<uint64_t> keepalives{0};
std::atomic<uint64_t> recent_activity{0};
std::atomic<uint64_t> real_in_flight{0};
std::atomic<uint64_t> keepalive_in_flight{0};
};

std::array<MockClientCounters, 256> g_mock_client_counters;

MockClientCounters& countersFor(folly::EventBase* evb) {
const auto address = reinterpret_cast<uintptr_t>(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(
Expand All @@ -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<std::exception>{}, [](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.
}
}
Expand All @@ -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<IdleKeepalivePolicy>(
keepalive_interval, IdleKeepalivePolicy::Clock::now())
: nullptr) {
if (evb_ == nullptr) {
throw std::invalid_argument(
"MockServicesClient: EventBase must not be null");
Expand Down Expand Up @@ -373,6 +401,27 @@ folly::SemiFuture<std::string> 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<std::string> MockServicesClient::dispatchByEnumImpl(
MethodIdx idx,
const std::string& request,
int32_t latency_us) {
// Compile-time switch over MethodIdx. Each case calls the named
// generated semifuture_<method>() so Strobelight sees distinct
// AsyncClient::send_<method> symbols — the whole reason we declared
Expand Down Expand Up @@ -429,4 +478,28 @@ folly::SemiFuture<std::string> 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::milliseconds>(
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
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
#include <folly/io/async/EventBase.h>

#include "RpcDistRegistry.h"
#include "MockClientPolicy.h"

// The generated cpp2 client is exposed as a `using` alias
// (`mock_services::MockServiceAsyncClient = apache::thrift::Client<...>`),
Expand All @@ -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
Expand Down Expand Up @@ -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<std::string> dispatchByEnumImpl(
MethodIdx idx, const std::string& request, int32_t latency_us);

folly::EventBase* evb_;
std::unique_ptr<mock_services::MockServiceAsyncClient> client_;
std::unique_ptr<KeepaliveTimer> keepalive_;
std::shared_ptr<IdleKeepalivePolicy> idle_keepalive_policy_;
};

/**
Expand Down
Loading