From a369385b52f185656905d2cd3683984d61452631 Mon Sep 17 00:00:00 2001 From: Erik Bylund Date: Mon, 23 Nov 2026 10:17:30 +0100 Subject: [PATCH 1/5] Add the client-side rate limiter The dual-threshold sliding window from D25, ported from the Unreal and Unity SDKs, which share the algorithm: - Tripwire: more than max_requests_per_tripwire in any rolling window. - Moving average: the per-bucket average across the whole window exceeds PerBucketLimit(), i.e. sustained traffic above moving_average_fraction of the tripwire rate. The soft cap exists because a pure tripwire lets a client sit at 279 requests a minute for ever - abusive, but never tripping. The moving average catches sustained near-limit behaviour the tripwire cannot see. A tripped request is HELD, not dropped and not failed. It stays queued and is promoted on a later Update() once the window clears, so the caller sees nothing. That is the difference between a throttle and an error, and it is why the limiter is checked in the promote phase rather than at submit: it counts requests actually sent, so a caller is not throttled for queueing work it never got to send. Server-side 429 is deliberately NOT the limiter's business. It is handled by the retry policy, and there is a test that proves the two are separate - with the limiter disabled, a 429 still retries and still reports RateLimited. Two behaviours worth recording, both taken from the reference implementations rather than invented: - The limiter clears when every counted request has aged out of the MOVING-AVERAGE window (180 s by default), not the tripwire window (60 s). A burst that trips the hard cap backs the client off for the full window. My first test asserted the shorter window and was wrong. - A held request is not counted. Counting it would keep the limiter tripped by its own backlog and the window would never drain. Verified by sabotage: disabling the gate in the promote loop fails five assertions. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- CMakeLists.txt | 1 + src/core/client.cpp | 4 +- src/core/executor.cpp | 26 ++- src/core/executor.h | 11 ++ src/core/rate_limiter.cpp | 173 ++++++++++++++++++++ src/core/rate_limiter.h | 104 ++++++++++++ tests/CMakeLists.txt | 6 + tests/test_executor.cpp | 123 ++++++++++++++ tests/test_rate_limiter.cpp | 315 ++++++++++++++++++++++++++++++++++++ 9 files changed, 759 insertions(+), 4 deletions(-) create mode 100644 src/core/rate_limiter.cpp create mode 100644 src/core/rate_limiter.h create mode 100644 tests/test_rate_limiter.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index b45f4ff..74c21c2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -140,6 +140,7 @@ add_library(lootlocker_core STATIC src/core/config_obfuscation.cpp src/core/header_map.cpp src/core/request_id.cpp + src/core/rate_limiter.cpp src/core/executor.cpp src/core/client.cpp ) diff --git a/src/core/client.cpp b/src/core/client.cpp index 2836cb4..bd4fbcf 100644 --- a/src/core/client.cpp +++ b/src/core/client.cpp @@ -77,8 +77,8 @@ Client::Client(const Config& config) : m_impl(new Impl()) #endif } - m_impl->executor.reset(new core::Executor(config.queue, transport, m_impl->clock, logger, - m_impl->config_error)); + m_impl->executor.reset(new core::Executor(config.queue, config.rate_limit, transport, + m_impl->clock, logger, m_impl->config_error)); } Client::~Client() = default; diff --git a/src/core/executor.cpp b/src/core/executor.cpp index b9f6657..7a7de36 100644 --- a/src/core/executor.cpp +++ b/src/core/executor.cpp @@ -43,14 +43,22 @@ bool IsRetryableStatus(int status_code) Executor::Executor(const QueueConfig& config, std::weak_ptr transport, Clock& clock, std::weak_ptr logger) : m_config(config), m_transport(std::move(transport)), m_clock(clock), - m_logger(std::move(logger)) + m_logger(std::move(logger)), m_rate_limiter(RateLimitConfig(), clock) { } Executor::Executor(const QueueConfig& config, std::weak_ptr transport, Clock& clock, std::weak_ptr logger, Error config_error) : m_config(config), m_config_error(std::move(config_error)), m_transport(std::move(transport)), - m_clock(clock), m_logger(std::move(logger)) + m_clock(clock), m_logger(std::move(logger)), m_rate_limiter(RateLimitConfig(), clock) +{ +} + +Executor::Executor(const QueueConfig& config, const RateLimitConfig& rate_limit, + std::weak_ptr transport, Clock& clock, + std::weak_ptr logger, Error config_error) + : m_config(config), m_config_error(std::move(config_error)), m_transport(std::move(transport)), + m_clock(clock), m_logger(std::move(logger)), m_rate_limiter(rate_limit, clock) { } @@ -479,6 +487,20 @@ bool Executor::Update() break; } + // The client-side throttle (D25). A tripped request is **held, not dropped**: + // it stays queued and is promoted on a later `Update()` once the window clears. + // The caller sees nothing until then, because a rate limit is self-restraint, + // not an error. + // + // Checked here rather than at submit time, because the limiter counts requests + // that are actually sent. Counting at submit would throttle a caller for + // queueing work it never got to send. + if (!m_rate_limiter.TryAcquire()) { + // Nothing else can be promoted either: the limiter is a global gate, so + // breaking here is correct and avoids a pointless loop over the rest. + break; + } + const auto it = m_entries.find(id); if (it == m_entries.end()) { continue; diff --git a/src/core/executor.h b/src/core/executor.h index f8836da..0603d33 100644 --- a/src/core/executor.h +++ b/src/core/executor.h @@ -18,6 +18,7 @@ #include #include "clock.h" +#include "rate_limiter.h" #include #include @@ -69,6 +70,12 @@ class Executor { // submission reject with it, which is how an inert client still delivers its handlers. Executor(const QueueConfig& config, std::weak_ptr transport, Clock& clock, std::weak_ptr logger, Error config_error); + + // The same, plus the rate limiter's policy (D25). The limiter is constructed from it and + // shares the executor's clock, so a test drives both with one fake. + Executor(const QueueConfig& config, const RateLimitConfig& rate_limit, + std::weak_ptr transport, Clock& clock, + std::weak_ptr logger, Error config_error); ~Executor(); Executor(const Executor&) = delete; @@ -171,6 +178,10 @@ class Executor { Clock& m_clock; std::weak_ptr m_logger; + // The client-side throttle (D25). Held by value: it is small, it shares the executor's + // clock, and it has no reason to outlive the executor. + RateLimiter m_rate_limiter; + std::map m_entries; // Handlers for requests rejected at submit time. Bounded by how many the caller diff --git a/src/core/rate_limiter.cpp b/src/core/rate_limiter.cpp new file mode 100644 index 0000000..789d1e2 --- /dev/null +++ b/src/core/rate_limiter.cpp @@ -0,0 +1,173 @@ +#include "rate_limiter.h" + +#include + +namespace lootlocker { +namespace core { + +namespace { + +// The bucket count and the per-bucket limit are derived from the config rather than stored, +// so the fraction and the effective limit cannot disagree. `floor`, not round: the soft +// threshold must never be more permissive than the fraction says, or a client could sit +// above the intended rate indefinitely. +int DeriveBucketCount(const RateLimitConfig& config) +{ + if (config.seconds_per_bucket <= 0 || config.tripwire_window_seconds <= 0) { + return 0; + } + const int buckets_per_tripwire = config.tripwire_window_seconds / config.seconds_per_bucket; + if (buckets_per_tripwire <= 0) { + return 0; + } + return buckets_per_tripwire * config.moving_average_time_frames; +} + +} // namespace + +RateLimiter::RateLimiter(const RateLimitConfig& config, Clock& clock) + : m_config(config), m_clock(clock) +{ + m_bucket_count = DeriveBucketCount(config); + if (m_bucket_count > 0) { + m_buckets_per_tripwire = config.tripwire_window_seconds / config.seconds_per_bucket; + m_per_bucket_limit = config.PerBucketLimit(); + m_buckets.assign(static_cast(m_bucket_count), 0); + } +} + +void RateLimiter::Reset() +{ + std::fill(m_buckets.begin(), m_buckets.end(), 0); + m_last_bucket = -1; + m_last_bucket_change_ms = 0; + m_started = false; + m_total = 0; + m_total_in_tripwire = 0; + m_limited = false; + m_resolves_at_ms = 0; +} + +void RateLimiter::Advance(std::int64_t now_ms) +{ + if (m_bucket_count <= 0) { + return; + } + + const std::int64_t bucket_ms = static_cast(m_config.seconds_per_bucket) * 1000; + + // The first call initialises bucket 0 rather than trying to measure elapsed time from a + // sentinel. + if (!m_started) { + m_started = true; + m_last_bucket = 0; + m_last_bucket_change_ms = now_ms; + return; + } + + const std::int64_t elapsed = now_ms - m_last_bucket_change_ms; + if (elapsed < bucket_ms) { + return; + } + + const std::int64_t moved = elapsed / bucket_ms; + + // Snap to the bucket boundary rather than the raw detection time, so sub-bucket + // remainder cannot accumulate as drift over a long run. + m_last_bucket_change_ms += moved * bucket_ms; + + // More buckets elapsed than exist: everything has aged out, so clear rather than + // looping over a window that is entirely stale. + if (moved >= m_bucket_count) { + std::fill(m_buckets.begin(), m_buckets.end(), 0); + m_total = 0; + m_total_in_tripwire = 0; + m_last_bucket = static_cast(moved % m_bucket_count); + return; + } + + for (std::int64_t step = 1; step <= moved; ++step) { + const int bucket = static_cast((m_last_bucket + step) % m_bucket_count); + + // The bucket exactly one tripwire window behind this one is sliding out of the + // tripwire window, so its count leaves that total. + int leaving_tripwire = bucket - m_buckets_per_tripwire; + if (leaving_tripwire < 0) { + leaving_tripwire += m_bucket_count; + } + + m_total_in_tripwire -= m_buckets[static_cast(leaving_tripwire)]; + m_total -= m_buckets[static_cast(bucket)]; + m_buckets[static_cast(bucket)] = 0; + } + + m_last_bucket = static_cast((m_last_bucket + moved) % m_bucket_count); +} + +bool RateLimiter::WouldTrip() const +{ + // Tripwire: this request would take the window to the cap. + if (m_total_in_tripwire + 1 > m_config.max_requests_per_tripwire) { + return true; + } + + // Moving average: the per-bucket average across the whole window would exceed the + // derived limit. Integer division, matching the reference implementations. + const int projected = m_total + 1; + return (projected / m_bucket_count) > m_per_bucket_limit; +} + +bool RateLimiter::TryAcquire() +{ + if (!m_config.enabled || m_bucket_count <= 0) { + return true; + } + + const std::int64_t now = m_clock.NowMs(); + Advance(now); + + // While limited, nothing is counted. A held request has not been sent, so counting it + // would keep the limiter tripped by its own backlog - the window would never drain. + if (m_limited) { + if (m_total <= 0) { + m_limited = false; + m_resolves_at_ms = 0; + } else { + return false; + } + } + + if (WouldTrip()) { + m_limited = true; + + // The limit clears once everything currently counted has aged out of the window. + // Derived from the current bucket boundary plus the full window, so the estimate + // does not drift with sub-bucket remainder. + const std::int64_t window_ms = + static_cast(m_bucket_count) * m_config.seconds_per_bucket * 1000; + m_resolves_at_ms = m_last_bucket_change_ms + window_ms; + return false; + } + + m_buckets[static_cast(m_last_bucket)]++; + m_total++; + m_total_in_tripwire++; + return true; +} + +int RateLimiter::SecondsUntilClear() const +{ + if (!m_limited) { + return 0; + } + const std::int64_t remaining = m_resolves_at_ms - m_clock.NowMs(); + if (remaining <= 0) { + return 0; + } + // Round up, so a caller that waits this long is not still limited by a fraction of a + // second. + return static_cast((remaining + 999) / 1000); +} + +} // namespace core +} // namespace lootlocker diff --git a/src/core/rate_limiter.h b/src/core/rate_limiter.h new file mode 100644 index 0000000..c5e98ec --- /dev/null +++ b/src/core/rate_limiter.h @@ -0,0 +1,104 @@ +#pragma once + +// The client-side rate limiter (D25). Internal: `lootlocker::core::` is not on an adopter's +// include path (D18). +// +// A dual-threshold sliding window, ported from the Unreal and Unity SDKs, which share the +// algorithm. Two thresholds, because one is not enough: +// +// Tripwire - hard cap: more than `max_requests_per_tripwire` in any rolling +// `tripwire_window_seconds` window. +// Moving average - soft cap: the per-bucket average across the whole window exceeds +// `PerBucketLimit()`, i.e. sustained traffic above +// `moving_average_fraction` of the tripwire rate. +// +// The soft cap exists because a pure tripwire lets a client sit at 279 requests a minute +// for ever: abusive, but never tripping. The moving average catches sustained near-limit +// behaviour that the tripwire cannot see. +// +// **This is client-side self-restraint, not error handling.** A tripped request is held and +// sent later, never dropped and never reported as an error. A server-side 429 is a different +// thing entirely and is handled by the executor's retry policy - conflating the two is how +// the other SDKs ended up with a limiter that also tries to be a retry policy. + +#include + +#include "clock.h" + +#include +#include + +namespace lootlocker { +namespace core { + +class RateLimiter { +public: + RateLimiter(const RateLimitConfig& config, Clock& clock); + + RateLimiter(const RateLimiter&) = delete; + RateLimiter& operator=(const RateLimiter&) = delete; + + // Records one request and returns true when it may be sent now. + // + // Returns false when the limiter is tripped, and records nothing in that case: a + // request that is not sent must not count against the window, or the limiter would + // keep itself tripped by counting the requests it is holding. + bool TryAcquire(); + + // True while the limiter is holding requests back. + bool IsLimited() const { return m_limited; } + + // Seconds until the limit is expected to clear. 0 when not limited. + // + // An estimate, not a promise: it is derived from when the oldest counted request ages + // out of the window, and the executor uses it only to decide when to look again. + int SecondsUntilClear() const; + + // Requests counted in the tripwire window, for tests and logs. + int TripwireCount() const { return m_total_in_tripwire; } + + // Requests counted across the whole moving-average window, for tests and logs. + int WindowCount() const { return m_total; } + + // Drops all state. For test isolation and for a client that is being reset. + void Reset(); + +private: + // Advances the bucket pointer to reflect elapsed time, zeroing the buckets that have + // slid out of the window and removing their counts from the running totals. + void Advance(std::int64_t now_ms); + + // Whether adding one more request would exceed either threshold. + bool WouldTrip() const; + + RateLimitConfig m_config; + Clock& m_clock; + + // Derived from the config at construction, so the arithmetic cannot disagree with + // itself later. + int m_bucket_count = 0; + int m_buckets_per_tripwire = 0; + int m_per_bucket_limit = 0; + + std::vector m_buckets; + + // Index of the most recently written bucket. -1 before the first request. + int m_last_bucket = -1; + + // When the current bucket became active, snapped to a bucket boundary so sub-bucket + // remainder cannot accumulate as drift. + std::int64_t m_last_bucket_change_ms = 0; + bool m_started = false; + + // Requests across every bucket in the array. + int m_total = 0; + + // Requests in the buckets that fall inside the current tripwire window. + int m_total_in_tripwire = 0; + + bool m_limited = false; + std::int64_t m_resolves_at_ms = 0; +}; + +} // namespace core +} // namespace lootlocker diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index c9f369c..ba1cda7 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -54,6 +54,12 @@ target_link_libraries(test_executor PRIVATE LootLocker::core lootlocker_compile_ target_include_directories(test_executor PRIVATE ${CMAKE_SOURCE_DIR}/src/core) add_test(NAME executor COMMAND test_executor) +# The rate limiter (T11a). Driven by a fake clock, so nothing sleeps. +add_executable(test_rate_limiter test_rate_limiter.cpp) +target_link_libraries(test_rate_limiter PRIVATE LootLocker::core lootlocker_compile_options) +target_include_directories(test_rate_limiter PRIVATE ${CMAKE_SOURCE_DIR}/src/core) +add_test(NAME rate_limiter COMMAND test_rate_limiter) + # The end-to-end transport test (T11, owner 2026-11-13): a real round trip through the real # curl transport against a loopback server, plus the proof that `Config::transport` is # actually consulted. diff --git a/tests/test_executor.cpp b/tests/test_executor.cpp index 7ff1e51..8e4bf61 100644 --- a/tests/test_executor.cpp +++ b/tests/test_executor.cpp @@ -30,6 +30,7 @@ class FakeClock : public Clock { public: std::int64_t NowMs() override { return m_now; } void Advance(std::int64_t ms) { m_now += ms; } + void AdvanceSeconds(int seconds) { m_now += static_cast(seconds) * 1000; } private: std::int64_t m_now = 1000; // non-zero, so "not set" is distinguishable @@ -1004,6 +1005,126 @@ void TestRequestIdNextIsUniqueUnderConcurrency() CHECK(all.front() != 0); } +// --- The rate limiter's integration with the queue (T11a) ------------------------------ + +// A fixture whose limiter is tight enough to trip in a few requests, so the integration is +// testable without 280 submissions. +struct LimitedFixture { + LimitedFixture() + : transport(std::make_shared()), + logger(std::make_shared()) + { + QueueConfig queue = DefaultQueue(); + queue.max_in_flight = 50; + + RateLimitConfig limit; + limit.enabled = true; + limit.tripwire_window_seconds = 10; + limit.max_requests_per_tripwire = 3; + limit.seconds_per_bucket = 10; + limit.moving_average_fraction = 1.0; + limit.moving_average_time_frames = 1; + + executor.reset(new Executor(queue, limit, transport, clock, logger, Error())); + } + + std::shared_ptr transport; + std::shared_ptr logger; + FakeClock clock; + std::unique_ptr executor; +}; + +void TestTrippedRequestIsHeldThenDelivered() +{ + LimitedFixture f; + + int delivered = 0; + for (int i = 0; i < 5; ++i) { + f.executor->Submit(Get("https://example.test/a" + std::to_string(i)), + [&delivered](const Completion&) { ++delivered; }); + } + + // The limiter allows 3 in the window, so only 3 are sent. The other 2 are held, not + // dropped and not failed. + CHECK(f.executor->Update()); + CHECK_EQ_INT(static_cast(f.transport->StartCount()), 3); + CHECK_EQ_INT(delivered, 0); + + // Complete the three that went out. + for (const auto transfer : f.transport->Order()) { + f.transport->Complete(transfer, 200, "{}"); + } + CHECK(f.executor->Update()); + CHECK_EQ_INT(delivered, 3); + + // The two held requests are still queued, and `Update()` still reports work to do - + // which is what stops a `while (Update())` loop from exiting early and losing them. + CHECK(f.executor->Update()); + CHECK_EQ_INT(static_cast(f.transport->StartCount()), 3); + + // Once the window clears they are sent, without the caller doing anything. + f.clock.AdvanceSeconds(11); + CHECK(f.executor->Update()); + CHECK_EQ_INT(static_cast(f.transport->StartCount()), 5); + + for (const auto transfer : f.transport->Order()) { + f.transport->Complete(transfer, 200, "{}"); + } + CHECK(!f.executor->Update()); + CHECK_EQ_INT(delivered, 5); +} + +void TestServerRateLimitIsHandledByRetryNotTheLimiter() +{ + // The limiter is disabled, so a 429 can only be handled by the retry policy. This is + // the separation D25 insists on: the limiter is client-side self-restraint, and a + // server 429 is a different thing entirely. + QueueConfig queue = DefaultQueue(); + queue.max_retries = 2; + + RateLimitConfig limit; + limit.enabled = false; + + auto transport = std::make_shared(); + auto logger = std::make_shared(); + FakeClock clock; + Executor executor(queue, limit, transport, clock, logger, Error()); + + int delivered = 0; + Completion last; + executor.Submit(Get("https://example.test/a"), [&](const Completion& c) { + ++delivered; + last = c; + }); + + CHECK(executor.Update()); + transport->Complete(transport->Order().back(), 429, "{}"); + CHECK(executor.Update()); + + // Retried by the retry policy, not held by the limiter. + CHECK_EQ_INT(delivered, 0); + clock.Advance(50); + CHECK(executor.Update()); + CHECK_EQ_INT(static_cast(transport->StartCount()), 2); + + // Attempt 2 fails the same way, so it is requeued again with a doubled delay. + transport->Complete(transport->Order().back(), 429, "{}"); + CHECK(executor.Update()); + CHECK_EQ_INT(delivered, 0); + clock.Advance(100); + CHECK(executor.Update()); + CHECK_EQ_INT(static_cast(transport->StartCount()), 3); + + // Attempt 3 exhausts the budget, so the failure is delivered. It is `RateLimited` + // because the server said so - the limiter is disabled and had no part in it. + transport->Complete(transport->Order().back(), 429, "{}"); + CHECK(!executor.Update()); + + CHECK_EQ_INT(delivered, 1); + CHECK(last.error.code == ErrorCode::RateLimited); + CHECK_EQ_INT(last.attempts, 3); +} + void TestAbandonCancelsInFlightWithoutCallingBack() { Fixture f; @@ -1062,6 +1183,8 @@ int main() TestRequestIdsAreUniqueAcrossClients(); TestRequestIdNextIsMonotonic(); TestRequestIdNextIsUniqueUnderConcurrency(); + TestTrippedRequestIsHeldThenDelivered(); + TestServerRateLimitIsHandledByRetryNotTheLimiter(); TestAbandonCancelsInFlightWithoutCallingBack(); return testing::Report(); diff --git a/tests/test_rate_limiter.cpp b/tests/test_rate_limiter.cpp new file mode 100644 index 0000000..c23db99 --- /dev/null +++ b/tests/test_rate_limiter.cpp @@ -0,0 +1,315 @@ +// The rate limiter (T11a, D25). +// +// Driven by a fake clock, so every timing assertion is exact and nothing sleeps. The +// algorithm is ported from the Unreal and Unity SDKs, so the tests are written against the +// behaviour those implementations have, not against a re-derivation of it. + +#include + +#include "clock.h" +#include "rate_limiter.h" +#include "test_harness.h" + +#include + +using namespace lootlocker; +using namespace lootlocker::core; + +namespace { + +class FakeClock : public Clock { +public: + std::int64_t NowMs() override { return m_now; } + void Advance(std::int64_t ms) { m_now += ms; } + void AdvanceSeconds(int seconds) { m_now += static_cast(seconds) * 1000; } + +private: + std::int64_t m_now = 1000000; // non-zero, so "not set" is distinguishable +}; + +RateLimitConfig Defaults() +{ + RateLimitConfig config; + config.enabled = true; + config.tripwire_window_seconds = 60; + config.max_requests_per_tripwire = 280; + config.seconds_per_bucket = 5; + config.moving_average_fraction = 0.8; + config.moving_average_time_frames = 3; + return config; +} + +// The derived values the defaults must produce, asserted once so a change to the derivation +// is visible rather than silently shifting every threshold. +void TestDerivedConstants() +{ + const RateLimitConfig config = Defaults(); + + // 280 * 0.8 * 5 / 60 = 18.67, floored to 18. + CHECK_EQ_INT(config.PerBucketLimit(), 18); +} + +// --- The tripwire ---------------------------------------------------------------------- + +void TestBurstTripsTheTripwire() +{ + FakeClock clock; + RateLimiter limiter(Defaults(), clock); + + // 280 requests in one bucket is allowed: the cap is "more than 280". + int allowed = 0; + for (int i = 0; i < 280; ++i) { + if (limiter.TryAcquire()) { + ++allowed; + } + } + CHECK_EQ_INT(allowed, 280); + CHECK(!limiter.IsLimited()); + + // The 281st trips it. + CHECK(!limiter.TryAcquire()); + CHECK(limiter.IsLimited()); + CHECK_EQ_INT(limiter.TripwireCount(), 280); +} + +void TestTripwireClearsWhenTheWindowSlides() +{ + FakeClock clock; + RateLimiter limiter(Defaults(), clock); + + for (int i = 0; i < 280; ++i) { + CHECK(limiter.TryAcquire()); + } + CHECK(!limiter.TryAcquire()); + CHECK(limiter.IsLimited()); + + // The tripwire window is 60 s, but the limiter does not clear when the tripwire window + // slides - it clears when every counted request has aged out of the *moving-average* + // window, which is 36 buckets of 5 s = 180 s. That is the reference behaviour in both + // the Unreal and Unity SDKs, and it is deliberately conservative: a burst that tripped + // the hard cap backs the client off for the full window rather than resuming the + // instant the 60 s count drops. + clock.AdvanceSeconds(59); + CHECK(!limiter.TryAcquire()); + CHECK(limiter.IsLimited()); + + clock.AdvanceSeconds(60); + CHECK(!limiter.TryAcquire()); + CHECK(limiter.IsLimited()); + + // Past the full window, the counted requests have aged out and the limiter clears. + clock.AdvanceSeconds(62); + CHECK(limiter.TryAcquire()); + CHECK(!limiter.IsLimited()); +} + +// --- The moving average ---------------------------------------------------------------- + +void TestSustainedTrafficTripsTheMovingAverage() +{ + FakeClock clock; + RateLimiter limiter(Defaults(), clock); + + // 18 requests per 5 s bucket is exactly the derived limit, so it must NOT trip: the + // check is "average exceeds 18", not "reaches 18". + // + // 36 buckets of 5 s is the whole window, so this is 3 minutes of traffic at exactly the + // soft cap. + for (int bucket = 0; bucket < 36; ++bucket) { + for (int i = 0; i < 18; ++i) { + CHECK(limiter.TryAcquire()); + } + clock.AdvanceSeconds(5); + } + CHECK(!limiter.IsLimited()); + + // One more per bucket pushes the average over 18 and trips the soft cap, even though + // the tripwire (280 per 60 s) is nowhere near. + for (int bucket = 0; bucket < 36; ++bucket) { + for (int i = 0; i < 19; ++i) { + if (!limiter.TryAcquire()) { + // Tripped partway through, which is the expected outcome. + CHECK(limiter.IsLimited()); + return; + } + } + clock.AdvanceSeconds(5); + } + + // Reaching here means it never tripped, which is the failure. + CHECK(limiter.IsLimited()); +} + +void TestMovingAverageTripsBelowTheTripwire() +{ + FakeClock clock; + RateLimiter limiter(Defaults(), clock); + + // 19 per bucket is 228 per 60 s, comfortably under the 280 tripwire. The soft cap is + // what catches it, which is the whole reason the soft cap exists. + bool tripped = false; + for (int bucket = 0; bucket < 36 && !tripped; ++bucket) { + for (int i = 0; i < 19; ++i) { + if (!limiter.TryAcquire()) { + tripped = true; + break; + } + } + clock.AdvanceSeconds(5); + } + + CHECK(tripped); + CHECK(limiter.IsLimited()); + + // And the tripwire count never reached its cap, so it was the average that caught it. + CHECK(limiter.TripwireCount() < 280); +} + +// --- A tripped request is held, not dropped -------------------------------------------- + +void TestHeldRequestsAreNotCounted() +{ + FakeClock clock; + RateLimiter limiter(Defaults(), clock); + + for (int i = 0; i < 280; ++i) { + CHECK(limiter.TryAcquire()); + } + CHECK(!limiter.TryAcquire()); + CHECK_EQ_INT(limiter.TripwireCount(), 280); + + // A held request must not count against the window, or the limiter would keep itself + // tripped by its own backlog and the window would never drain. + for (int i = 0; i < 100; ++i) { + CHECK(!limiter.TryAcquire()); + } + CHECK_EQ_INT(limiter.TripwireCount(), 280); + + // So it still clears on schedule - the full moving-average window, not the tripwire + // window. + clock.AdvanceSeconds(181); + CHECK(limiter.TryAcquire()); +} + +void TestSecondsUntilClearIsAnEstimateThatExpires() +{ + FakeClock clock; + RateLimiter limiter(Defaults(), clock); + + CHECK_EQ_INT(limiter.SecondsUntilClear(), 0); + + for (int i = 0; i < 280; ++i) { + CHECK(limiter.TryAcquire()); + } + CHECK(!limiter.TryAcquire()); + + // The window is 3 minutes (36 buckets of 5 s), so the estimate is bounded by that. + const int estimate = limiter.SecondsUntilClear(); + CHECK(estimate > 0); + CHECK(estimate <= 180); + + // Waiting the estimate out clears it. + clock.AdvanceSeconds(estimate); + CHECK(limiter.TryAcquire()); + CHECK_EQ_INT(limiter.SecondsUntilClear(), 0); +} + +// --- Disabled, and the config edge cases ----------------------------------------------- + +void TestDisabledLimiterAlwaysAllows() +{ + RateLimitConfig config = Defaults(); + config.enabled = false; + + FakeClock clock; + RateLimiter limiter(config, clock); + + // Far past every threshold, and still allowed. + for (int i = 0; i < 10000; ++i) { + CHECK(limiter.TryAcquire()); + } + CHECK(!limiter.IsLimited()); +} + +void TestResetClearsEverything() +{ + FakeClock clock; + RateLimiter limiter(Defaults(), clock); + + for (int i = 0; i < 280; ++i) { + CHECK(limiter.TryAcquire()); + } + CHECK(!limiter.TryAcquire()); + CHECK(limiter.IsLimited()); + + limiter.Reset(); + + CHECK(!limiter.IsLimited()); + CHECK_EQ_INT(limiter.TripwireCount(), 0); + CHECK_EQ_INT(limiter.WindowCount(), 0); + CHECK(limiter.TryAcquire()); +} + +void TestLongIdlePeriodClearsWithoutIterating() +{ + FakeClock clock; + RateLimiter limiter(Defaults(), clock); + + for (int i = 0; i < 280; ++i) { + CHECK(limiter.TryAcquire()); + } + CHECK(!limiter.TryAcquire()); + + // A day of idleness is far more buckets than exist. The limiter must clear rather than + // loop over a window that is entirely stale. + clock.AdvanceSeconds(86400); + CHECK(limiter.TryAcquire()); + CHECK(!limiter.IsLimited()); + CHECK_EQ_INT(limiter.TripwireCount(), 1); +} + +void TestCustomConstantsAreHonoured() +{ + // The constants are policy, not a constexpr in a header, so a different policy must + // work. 10 per 10 s, one bucket per 10 s, one frame. + RateLimitConfig config; + config.enabled = true; + config.tripwire_window_seconds = 10; + config.max_requests_per_tripwire = 10; + config.seconds_per_bucket = 10; + config.moving_average_fraction = 1.0; + config.moving_average_time_frames = 1; + FakeClock clock; + RateLimiter limiter(config, clock); + + int allowed = 0; + for (int i = 0; i < 10; ++i) { + if (limiter.TryAcquire()) { + ++allowed; + } + } + CHECK_EQ_INT(allowed, 10); + CHECK(!limiter.TryAcquire()); + + clock.AdvanceSeconds(11); + CHECK(limiter.TryAcquire()); +} + +} // namespace + +int main() +{ + TestDerivedConstants(); + TestBurstTripsTheTripwire(); + TestTripwireClearsWhenTheWindowSlides(); + TestSustainedTrafficTripsTheMovingAverage(); + TestMovingAverageTripsBelowTheTripwire(); + TestHeldRequestsAreNotCounted(); + TestSecondsUntilClearIsAnEstimateThatExpires(); + TestDisabledLimiterAlwaysAllows(); + TestResetClearsEverything(); + TestLongIdlePeriodClearsWithoutIterating(); + TestCustomConstantsAreHonoured(); + + return testing::Report(); +} From f1524cdc39e92e660568763a4c7f4c7ed705042d Mon Sep 17 00:00:00 2001 From: Erik Bylund Date: Mon, 23 Nov 2026 10:43:12 +0100 Subject: [PATCH 2/5] Fix four review findings in the rate limiter - The limiter recorded a request BEFORE calling Start, so a Start that returned 0 burned quota for a request that never left. Repeated failures could hold unrelated queued requests, contradicting the "counts requests actually sent" contract. Split into CanAcquire() and Commit(), and the executor commits only after the transfer actually started. Verified by sabotage: with the old ordering only 3 of 10 requests are delivered, the rest held by a limiter that thinks it sent them. - DeriveBucketCount could overflow int on the multiply, and a negative bucket count takes the "disabled" fast path - silently turning the limiter off for a config that looked valid. The multiply is now checked before it happens. - A non-divisible policy silently shortened the window: 60 s with 7 s buckets became an effective 56 s tripwire and 168 s moving average while the config still advertised 60/180. Rejected rather than rounded, because a different rate limit than the adopter asked for is worse than a clear refusal. - RequestId::Next wrapped UINT64_MAX to 0, storing the invalid sentinel, so the NEXT call returned RequestId(0) - indistinguishable from a rejected submission and colliding with that map key. Now wraps to 1. Both rejections make the limiter inert rather than misconfigured, which is the safe direction: a broken policy must not throttle a game. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/core/executor.cpp | 7 ++++- src/core/rate_limiter.cpp | 42 +++++++++++++++++++++++-- src/core/rate_limiter.h | 16 ++++++++-- src/core/request_id.cpp | 13 +++++--- tests/test_executor.cpp | 42 +++++++++++++++++++++++++ tests/test_rate_limiter.cpp | 62 +++++++++++++++++++++++++++++++++++++ 6 files changed, 172 insertions(+), 10 deletions(-) diff --git a/src/core/executor.cpp b/src/core/executor.cpp index 7a7de36..100d5e5 100644 --- a/src/core/executor.cpp +++ b/src/core/executor.cpp @@ -495,7 +495,7 @@ bool Executor::Update() // Checked here rather than at submit time, because the limiter counts requests // that are actually sent. Counting at submit would throttle a caller for // queueing work it never got to send. - if (!m_rate_limiter.TryAcquire()) { + if (!m_rate_limiter.CanAcquire()) { // Nothing else can be promoted either: the limiter is a global gate, so // breaking here is correct and avoids a pointless loop over the rest. break; @@ -540,6 +540,11 @@ bool Executor::Update() entry.transfer = transfer; entry.in_flight = true; + + // Recorded only now, after the transfer actually started. A `Start` that + // returned 0 sent nothing, so counting it would burn quota for a request that + // never left - and repeated failures could hold unrelated queued requests. + m_rate_limiter.Commit(); } } diff --git a/src/core/rate_limiter.cpp b/src/core/rate_limiter.cpp index 789d1e2..57dd3fb 100644 --- a/src/core/rate_limiter.cpp +++ b/src/core/rate_limiter.cpp @@ -11,15 +11,37 @@ namespace { // so the fraction and the effective limit cannot disagree. `floor`, not round: the soft // threshold must never be more permissive than the fraction says, or a client could sit // above the intended rate indefinitely. +// +// Returns 0 for a configuration that cannot produce a usable window. That includes one whose +// product would overflow `int`: a large `moving_average_time_frames` with a large bucket +// count would otherwise wrap negative, and a negative bucket count takes the "disabled" fast +// path - silently turning the limiter off for a config that looked valid. int DeriveBucketCount(const RateLimitConfig& config) { - if (config.seconds_per_bucket <= 0 || config.tripwire_window_seconds <= 0) { + if (config.seconds_per_bucket <= 0 || config.tripwire_window_seconds <= 0 + || config.moving_average_time_frames <= 0) { return 0; } + + // Reject a non-divisible policy rather than silently shortening the window. 60 s with + // 7 s buckets would otherwise become an effective 56 s tripwire and a 168 s moving + // average, while the config still advertises 60/180 - a different rate limit than the + // adopter asked for, with nothing to say so. + if (config.tripwire_window_seconds % config.seconds_per_bucket != 0) { + return 0; + } + const int buckets_per_tripwire = config.tripwire_window_seconds / config.seconds_per_bucket; if (buckets_per_tripwire <= 0) { return 0; } + + // Checked before multiplying, not after: the multiply itself is the undefined behaviour. + const int max_int = 2147483647; + if (buckets_per_tripwire > max_int / config.moving_average_time_frames) { + return 0; + } + return buckets_per_tripwire * config.moving_average_time_frames; } @@ -117,7 +139,7 @@ bool RateLimiter::WouldTrip() const return (projected / m_bucket_count) > m_per_bucket_limit; } -bool RateLimiter::TryAcquire() +bool RateLimiter::CanAcquire() { if (!m_config.enabled || m_bucket_count <= 0) { return true; @@ -149,9 +171,25 @@ bool RateLimiter::TryAcquire() return false; } + return true; +} + +void RateLimiter::Commit() +{ + if (!m_config.enabled || m_bucket_count <= 0) { + return; + } m_buckets[static_cast(m_last_bucket)]++; m_total++; m_total_in_tripwire++; +} + +bool RateLimiter::TryAcquire() +{ + if (!CanAcquire()) { + return false; + } + Commit(); return true; } diff --git a/src/core/rate_limiter.h b/src/core/rate_limiter.h index c5e98ec..1b9e87f 100644 --- a/src/core/rate_limiter.h +++ b/src/core/rate_limiter.h @@ -38,11 +38,21 @@ class RateLimiter { RateLimiter(const RateLimiter&) = delete; RateLimiter& operator=(const RateLimiter&) = delete; + // Whether a request may be sent now. Does not record anything. + // + // Split from `Commit` so the executor can check *before* starting a transfer and record + // only if the transfer actually started. `IHttpTransport::Start` may return 0, and a + // start that failed sent nothing - counting it would burn quota for a request that never + // left, and repeated failures could hold unrelated queued requests. + bool CanAcquire(); + // Records one request against the window. Call only after `CanAcquire()` returned true + // and the transfer actually started. + void Commit(); + // Records one request and returns true when it may be sent now. // - // Returns false when the limiter is tripped, and records nothing in that case: a - // request that is not sent must not count against the window, or the limiter would - // keep itself tripped by counting the requests it is holding. + // Convenience for a caller that has nothing between the check and the send. The executor + // does not use it, because it has a `Start` call in between. bool TryAcquire(); // True while the limiter is holding requests back. diff --git a/src/core/request_id.cpp b/src/core/request_id.cpp index cc962ab..ea8800e 100644 --- a/src/core/request_id.cpp +++ b/src/core/request_id.cpp @@ -27,10 +27,15 @@ RequestId RequestId::Next() // `fetch_add` it replaces. std::uint64_t current = g_next_request_id.load(std::memory_order_relaxed); for (;;) { - // Skip 0, which is the invalid id. Unreachable in practice - a uint64 at a million - // requests a second lasts longer than the hardware - but the loop makes the wrap - // safe by construction rather than by argument. - const std::uint64_t next = (current == 0) ? 1 : current + 1; + // Skip 0, which is the invalid id, and wrap from the maximum back to 1 rather than + // to 0. `current + 1` alone would store 0 at the wrap, and the *next* call would + // then return `RequestId(0)` - which is indistinguishable from a rejected + // submission and would collide with that map key. + // + // Unreachable in practice - a uint64 at a million requests a second lasts longer + // than the hardware - but the loop makes the invariant true by construction rather + // than by argument. + const std::uint64_t next = (current == 0 || current == UINT64_MAX) ? 1 : current + 1; if (g_next_request_id.compare_exchange_weak(current, next, std::memory_order_relaxed, std::memory_order_relaxed)) { diff --git a/tests/test_executor.cpp b/tests/test_executor.cpp index 8e4bf61..7b24da5 100644 --- a/tests/test_executor.cpp +++ b/tests/test_executor.cpp @@ -1125,6 +1125,47 @@ void TestServerRateLimitIsHandledByRetryNotTheLimiter() CHECK_EQ_INT(last.attempts, 3); } +// A transport that refuses to start anything, so the executor's start-failure path can be +// exercised. +class RefusingTransport : public IHttpTransport { +public: + TransferId Start(const Request&) override { return 0; } + bool Poll(TransferId, Response&) override { return false; } + void Cancel(TransferId) override {} +}; + +void TestFailedStartDoesNotBurnQuota() +{ + // The limiter allows 3 in the window. Every start fails, so nothing is ever sent - and + // nothing should be counted. Counting a failed start would burn quota for a request that + // never left, and repeated failures could hold unrelated queued requests. + QueueConfig queue = DefaultQueue(); + queue.max_retries = 0; + + RateLimitConfig limit; + limit.enabled = true; + limit.tripwire_window_seconds = 10; + limit.max_requests_per_tripwire = 3; + limit.seconds_per_bucket = 10; + limit.moving_average_fraction = 1.0; + limit.moving_average_time_frames = 1; + + auto transport = std::make_shared(); + auto logger = std::make_shared(); + FakeClock clock; + Executor executor(queue, limit, transport, clock, logger, Error()); + + int delivered = 0; + for (int i = 0; i < 10; ++i) { + executor.Submit(Get("https://example.test/a" + std::to_string(i)), + [&delivered](const Completion&) { ++delivered; }); + } + + // Every one fails to start, so every one is delivered as a transport failure rather than + // being held by a limiter that thinks it sent something. + executor.Update(); + CHECK_EQ_INT(delivered, 10); +} void TestAbandonCancelsInFlightWithoutCallingBack() { Fixture f; @@ -1185,6 +1226,7 @@ int main() TestRequestIdNextIsUniqueUnderConcurrency(); TestTrippedRequestIsHeldThenDelivered(); TestServerRateLimitIsHandledByRetryNotTheLimiter(); + TestFailedStartDoesNotBurnQuota(); TestAbandonCancelsInFlightWithoutCallingBack(); return testing::Report(); diff --git a/tests/test_rate_limiter.cpp b/tests/test_rate_limiter.cpp index c23db99..ef50be9 100644 --- a/tests/test_rate_limiter.cpp +++ b/tests/test_rate_limiter.cpp @@ -295,6 +295,65 @@ void TestCustomConstantsAreHonoured() CHECK(limiter.TryAcquire()); } +void TestNonDivisiblePolicyIsRejected() +{ + // 60 s with 7 s buckets does not divide. Silently shortening it would give an effective + // 56 s tripwire and a 168 s moving average while the config still advertises 60/180 - + // a different rate limit than the adopter asked for, with nothing to say so. + RateLimitConfig config = Defaults(); + config.seconds_per_bucket = 7; + + FakeClock clock; + RateLimiter limiter(config, clock); + + // Rejected means the limiter is inert rather than silently misconfigured. It allows + // everything, which is the safe direction: a broken policy must not throttle a game. + for (int i = 0; i < 1000; ++i) { + CHECK(limiter.TryAcquire()); + } + CHECK(!limiter.IsLimited()); +} + +void TestOverflowingBucketCountIsRejected() +{ + // A large frame count with a large bucket count would overflow `int` on the multiply and + // wrap negative - and a negative bucket count takes the "disabled" fast path, silently + // turning the limiter off for a config that looked valid. + RateLimitConfig config = Defaults(); + config.tripwire_window_seconds = 2000000000; + config.seconds_per_bucket = 1; + config.moving_average_time_frames = 100; + + FakeClock clock; + RateLimiter limiter(config, clock); + + // Inert rather than negative, and no huge allocation. + for (int i = 0; i < 1000; ++i) { + CHECK(limiter.TryAcquire()); + } + CHECK(!limiter.IsLimited()); +} +void TestCommitIsSeparateFromTheCheck() +{ + // The executor checks, starts the transfer, and only then commits - because a `Start` + // that returned 0 sent nothing. This is the primitive that makes that possible. + FakeClock clock; + RateLimiter limiter(Defaults(), clock); + + CHECK(limiter.CanAcquire()); + CHECK_EQ_INT(limiter.TripwireCount(), 0); // checking alone records nothing + + limiter.Commit(); + CHECK_EQ_INT(limiter.TripwireCount(), 1); + + // A check that is never committed leaves the window untouched, so a failed start cannot + // burn quota. + for (int i = 0; i < 500; ++i) { + CHECK(limiter.CanAcquire()); + } + CHECK_EQ_INT(limiter.TripwireCount(), 1); +} + } // namespace int main() @@ -310,6 +369,9 @@ int main() TestResetClearsEverything(); TestLongIdlePeriodClearsWithoutIterating(); TestCustomConstantsAreHonoured(); + TestNonDivisiblePolicyIsRejected(); + TestOverflowingBucketCountIsRejected(); + TestCommitIsSeparateFromTheCheck(); return testing::Report(); } From 22d3d9ddafa6b60a67108c4008971d4793e3a248 Mon Sep 17 00:00:00 2001 From: Erik Bylund Date: Tue, 24 Nov 2026 14:56:57 +0100 Subject: [PATCH 3/5] Restructure the limiter around a tick, and make its state atomic Six review comments, all acted on. - One Executor constructor instead of three. There are no users yet, so there is nothing to keep compatible, and three overloads that differ by a trailing argument are harder to read than one ExecutorSettings struct. - The limiter is now TICKED, not clock-reading. It used to call the clock from inside CanAcquire(), which made a const-looking predicate mutate the whole module and meant the window only advanced when someone happened to ask. The executor owns the clock and pushes a delta into every tickable component; the limiter keeps a remainder rather than an absolute timestamp, so sub-bucket time still carries forward. - CanAcquire() is const, as its name says. It reads and reports; Commit() records. The trip is detected in Commit, after the increment, so the request that REACHES the cap is allowed and the next one is held - the cap is "more than 280", not "280". - IsLimited() is derived (m_limited && m_total > 0) rather than stored. A stored flag has to be cleared by something, and the only method that runs after a successful check is Commit - so a caller that only ever checked saw a stale true for ever. - Explicit names: numberOfBucketsTraversed rather than moved, ms_into_bucket rather than elapsed. - Atomics on every primitive, relaxed ordering. The SDK is single-threaded by contract but not by enforcement: a game that called Update() from two threads would otherwise corrupt the window silently, and a torn read is a wrong rate limit rather than a crash - the kind of bug that shows up as "the limiter randomly trips" months later. No locks: no invariant spans two fields, so a mutex would add contention to buy nothing. The bucket array is a unique_ptr[]> because std::atomic is neither copyable nor movable, so a vector cannot hold it. Two bugs found while doing this, both caught by the tests: - Commit wrote to m_buckets[-1] when the limiter had not been ticked yet. That is a stack overrun, not a wrong number - it crashed three test binaries with 0xc0000409. Tick now initialises bucket 0 even with a zero delta, and Commit guards anyway. - IsLimited() and CanAcquire() disagreed for exactly one request, because the check tripped before the commit recorded it. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/core/client.cpp | 11 +- src/core/executor.cpp | 30 ++---- src/core/executor.h | 47 ++++++--- src/core/rate_limiter.cpp | 201 ++++++++++++++++++++++-------------- src/core/rate_limiter.h | 87 +++++++++++----- tests/test_executor.cpp | 39 ++++++- tests/test_rate_limiter.cpp | 119 +++++++++++++-------- 7 files changed, 348 insertions(+), 186 deletions(-) diff --git a/src/core/client.cpp b/src/core/client.cpp index bd4fbcf..ca21747 100644 --- a/src/core/client.cpp +++ b/src/core/client.cpp @@ -77,8 +77,15 @@ Client::Client(const Config& config) : m_impl(new Impl()) #endif } - m_impl->executor.reset(new core::Executor(config.queue, config.rate_limit, transport, - m_impl->clock, logger, m_impl->config_error)); + core::ExecutorSettings settings; + settings.queue = config.queue; + settings.rate_limit = config.rate_limit; + settings.transport = transport; + settings.clock = &m_impl->clock; + settings.logger = logger; + settings.config_error = m_impl->config_error; + + m_impl->executor.reset(new core::Executor(settings)); } Client::~Client() = default; diff --git a/src/core/executor.cpp b/src/core/executor.cpp index 100d5e5..43521c1 100644 --- a/src/core/executor.cpp +++ b/src/core/executor.cpp @@ -40,25 +40,10 @@ bool IsRetryableStatus(int status_code) } // namespace -Executor::Executor(const QueueConfig& config, std::weak_ptr transport, - Clock& clock, std::weak_ptr logger) - : m_config(config), m_transport(std::move(transport)), m_clock(clock), - m_logger(std::move(logger)), m_rate_limiter(RateLimitConfig(), clock) -{ -} - -Executor::Executor(const QueueConfig& config, std::weak_ptr transport, - Clock& clock, std::weak_ptr logger, Error config_error) - : m_config(config), m_config_error(std::move(config_error)), m_transport(std::move(transport)), - m_clock(clock), m_logger(std::move(logger)), m_rate_limiter(RateLimitConfig(), clock) -{ -} - -Executor::Executor(const QueueConfig& config, const RateLimitConfig& rate_limit, - std::weak_ptr transport, Clock& clock, - std::weak_ptr logger, Error config_error) - : m_config(config), m_config_error(std::move(config_error)), m_transport(std::move(transport)), - m_clock(clock), m_logger(std::move(logger)), m_rate_limiter(rate_limit, clock) +Executor::Executor(const ExecutorSettings& settings) + : m_config(settings.queue), m_config_error(settings.config_error), + m_transport(settings.transport), m_clock(*settings.clock), m_logger(settings.logger), + m_rate_limiter(settings.rate_limit, *settings.clock) { } @@ -360,6 +345,13 @@ bool Executor::Update() const std::int64_t now = m_clock.NowMs(); + // The executor is the one place that reads the clock, and it pushes the delta into every + // tickable component. A component that read the clock itself would advance only when + // someone happened to ask it something, which is how the limiter used to work. + const std::int64_t delta_ms = (m_last_tick_ms == 0) ? 0 : now - m_last_tick_ms; + m_last_tick_ms = now; + m_rate_limiter.Tick(delta_ms); + std::vector handlers; std::vector completions; diff --git a/src/core/executor.h b/src/core/executor.h index 0603d33..aa3bb38 100644 --- a/src/core/executor.h +++ b/src/core/executor.h @@ -61,21 +61,36 @@ struct Completion { using CompletionHandler = std::function; +// Everything the executor needs to be constructed. +// +// A struct rather than a parameter list, because the executor has five dependencies and +// three of them are optional. Three overloads existed to avoid naming the optional ones; +// with no users yet there is nothing to keep compatible, and one shape is easier to read +// and to extend than three that differ by a trailing argument. +struct ExecutorSettings { + QueueConfig queue; + + // The rate limiter's policy (D25). Defaults are the production values, so a caller that + // does not care gets the real limiter rather than a disabled one. + RateLimitConfig rate_limit; + + // The transport. Empty means "none available", which the executor reports rather than + // crashing on - a build without curl and no injected transport is a supported state. + std::weak_ptr transport; + + // The clock. Never null: the executor dereferences it, and a test supplies a fake. + Clock* clock = nullptr; + + std::weak_ptr logger; + + // Empty when the config was usable. A non-empty error makes every submission reject with + // it, which is how an inert client still delivers its handlers. + Error config_error; +}; + class Executor { public: - Executor(const QueueConfig& config, std::weak_ptr transport, Clock& clock, - std::weak_ptr logger); - - // The same, plus the config error the client found. A non-empty error makes every - // submission reject with it, which is how an inert client still delivers its handlers. - Executor(const QueueConfig& config, std::weak_ptr transport, Clock& clock, - std::weak_ptr logger, Error config_error); - - // The same, plus the rate limiter's policy (D25). The limiter is constructed from it and - // shares the executor's clock, so a test drives both with one fake. - Executor(const QueueConfig& config, const RateLimitConfig& rate_limit, - std::weak_ptr transport, Clock& clock, - std::weak_ptr logger, Error config_error); + explicit Executor(const ExecutorSettings& settings); ~Executor(); Executor(const Executor&) = delete; @@ -178,8 +193,10 @@ class Executor { Clock& m_clock; std::weak_ptr m_logger; - // The client-side throttle (D25). Held by value: it is small, it shares the executor's - // clock, and it has no reason to outlive the executor. + std::int64_t m_last_tick_ms = 0; + + // The client-side throttle (D25). Held by value: it is small, it is ticked by `Update()`, + // and it has no reason to outlive the executor. RateLimiter m_rate_limiter; std::map m_entries; diff --git a/src/core/rate_limiter.cpp b/src/core/rate_limiter.cpp index 57dd3fb..251f922 100644 --- a/src/core/rate_limiter.cpp +++ b/src/core/rate_limiter.cpp @@ -54,62 +54,100 @@ RateLimiter::RateLimiter(const RateLimitConfig& config, Clock& clock) if (m_bucket_count > 0) { m_buckets_per_tripwire = config.tripwire_window_seconds / config.seconds_per_bucket; m_per_bucket_limit = config.PerBucketLimit(); - m_buckets.assign(static_cast(m_bucket_count), 0); + + // A fixed-size array, allocated once. `std::atomic` is neither copyable nor movable, + // so a vector cannot hold it. + m_buckets.reset(new std::atomic[static_cast(m_bucket_count)]); + for (int i = 0; i < m_bucket_count; ++i) { + m_buckets[static_cast(i)].store(0, std::memory_order_relaxed); + } } } void RateLimiter::Reset() { - std::fill(m_buckets.begin(), m_buckets.end(), 0); - m_last_bucket = -1; - m_last_bucket_change_ms = 0; - m_started = false; - m_total = 0; - m_total_in_tripwire = 0; - m_limited = false; - m_resolves_at_ms = 0; + for (int i = 0; i < m_bucket_count; ++i) { + m_buckets[static_cast(i)].store(0, std::memory_order_relaxed); + } + m_last_bucket.store(-1, std::memory_order_relaxed); + m_ms_into_bucket.store(0, std::memory_order_relaxed); + m_started.store(false, std::memory_order_relaxed); + m_total.store(0, std::memory_order_relaxed); + m_total_in_tripwire.store(0, std::memory_order_relaxed); + m_limited.store(false, std::memory_order_relaxed); + m_ms_until_clear.store(0, std::memory_order_relaxed); } -void RateLimiter::Advance(std::int64_t now_ms) +void RateLimiter::Tick(std::int64_t delta_ms) { if (m_bucket_count <= 0) { return; } - const std::int64_t bucket_ms = static_cast(m_config.seconds_per_bucket) * 1000; + // The first tick initialises bucket 0, even with a zero delta. Without this the limiter + // would stay unstarted until time actually passed, and `Commit` would write to bucket -1. + if (!m_started.load(std::memory_order_relaxed)) { + m_started.store(true, std::memory_order_relaxed); + m_last_bucket.store(0, std::memory_order_relaxed); + m_ms_into_bucket.store(0, std::memory_order_relaxed); + return; + } - // The first call initialises bucket 0 rather than trying to measure elapsed time from a - // sentinel. - if (!m_started) { - m_started = true; - m_last_bucket = 0; - m_last_bucket_change_ms = now_ms; + if (delta_ms <= 0) { return; } - const std::int64_t elapsed = now_ms - m_last_bucket_change_ms; - if (elapsed < bucket_ms) { + // The countdown to clearing is a duration, so it simply decreases. Clamped at zero so a + // long idle period cannot make it negative and then take a whole window to climb back. + if (m_limited.load(std::memory_order_relaxed)) { + std::int64_t remaining = m_ms_until_clear.load(std::memory_order_relaxed) - delta_ms; + if (remaining < 0) { + remaining = 0; + } + m_ms_until_clear.store(remaining, std::memory_order_relaxed); + } + + SlideWindow(delta_ms); +} + +void RateLimiter::SlideWindow(std::int64_t delta_ms) +{ + const std::int64_t bucket_ms = static_cast(m_config.seconds_per_bucket) * 1000; + + const std::int64_t ms_into_bucket = + m_ms_into_bucket.load(std::memory_order_relaxed) + delta_ms; + + const std::int64_t numberOfBucketsTraversed = ms_into_bucket / bucket_ms; + if (numberOfBucketsTraversed == 0) { + m_ms_into_bucket.store(ms_into_bucket, std::memory_order_relaxed); return; } - const std::int64_t moved = elapsed / bucket_ms; + // Keep only the remainder, so sub-bucket time carries forward and cannot accumulate as + // drift over a long run. + m_ms_into_bucket.store(ms_into_bucket - numberOfBucketsTraversed * bucket_ms, + std::memory_order_relaxed); - // Snap to the bucket boundary rather than the raw detection time, so sub-bucket - // remainder cannot accumulate as drift over a long run. - m_last_bucket_change_ms += moved * bucket_ms; + const int last_bucket = m_last_bucket.load(std::memory_order_relaxed); - // More buckets elapsed than exist: everything has aged out, so clear rather than - // looping over a window that is entirely stale. - if (moved >= m_bucket_count) { - std::fill(m_buckets.begin(), m_buckets.end(), 0); - m_total = 0; - m_total_in_tripwire = 0; - m_last_bucket = static_cast(moved % m_bucket_count); + // More buckets elapsed than exist: everything has aged out, so clear rather than looping + // over a window that is entirely stale. + if (numberOfBucketsTraversed >= m_bucket_count) { + for (int i = 0; i < m_bucket_count; ++i) { + m_buckets[static_cast(i)].store(0, std::memory_order_relaxed); + } + m_total.store(0, std::memory_order_relaxed); + m_total_in_tripwire.store(0, std::memory_order_relaxed); + m_last_bucket.store(static_cast(numberOfBucketsTraversed % m_bucket_count), + std::memory_order_relaxed); return; } - for (std::int64_t step = 1; step <= moved; ++step) { - const int bucket = static_cast((m_last_bucket + step) % m_bucket_count); + int total = m_total.load(std::memory_order_relaxed); + int total_in_tripwire = m_total_in_tripwire.load(std::memory_order_relaxed); + + for (std::int64_t step = 1; step <= numberOfBucketsTraversed; ++step) { + const int bucket = static_cast((last_bucket + step) % m_bucket_count); // The bucket exactly one tripwire window behind this one is sliding out of the // tripwire window, so its count leaves that total. @@ -118,60 +156,45 @@ void RateLimiter::Advance(std::int64_t now_ms) leaving_tripwire += m_bucket_count; } - m_total_in_tripwire -= m_buckets[static_cast(leaving_tripwire)]; - m_total -= m_buckets[static_cast(bucket)]; - m_buckets[static_cast(bucket)] = 0; + total_in_tripwire -= m_buckets[static_cast(leaving_tripwire)].load( + std::memory_order_relaxed); + total -= m_buckets[static_cast(bucket)].load(std::memory_order_relaxed); + m_buckets[static_cast(bucket)].store(0, std::memory_order_relaxed); } - m_last_bucket = static_cast((m_last_bucket + moved) % m_bucket_count); + m_total.store(total, std::memory_order_relaxed); + m_total_in_tripwire.store(total_in_tripwire, std::memory_order_relaxed); + m_last_bucket.store(static_cast((last_bucket + numberOfBucketsTraversed) % m_bucket_count), + std::memory_order_relaxed); } bool RateLimiter::WouldTrip() const { // Tripwire: this request would take the window to the cap. - if (m_total_in_tripwire + 1 > m_config.max_requests_per_tripwire) { + if (m_total_in_tripwire.load(std::memory_order_relaxed) + 1 + > m_config.max_requests_per_tripwire) { return true; } // Moving average: the per-bucket average across the whole window would exceed the // derived limit. Integer division, matching the reference implementations. - const int projected = m_total + 1; + const int projected = m_total.load(std::memory_order_relaxed) + 1; return (projected / m_bucket_count) > m_per_bucket_limit; } -bool RateLimiter::CanAcquire() +bool RateLimiter::CanAcquire() const { if (!m_config.enabled || m_bucket_count <= 0) { return true; } - const std::int64_t now = m_clock.NowMs(); - Advance(now); - // While limited, nothing is counted. A held request has not been sent, so counting it // would keep the limiter tripped by its own backlog - the window would never drain. - if (m_limited) { - if (m_total <= 0) { - m_limited = false; - m_resolves_at_ms = 0; - } else { - return false; - } + if (m_limited.load(std::memory_order_relaxed)) { + return m_total.load(std::memory_order_relaxed) <= 0; } - if (WouldTrip()) { - m_limited = true; - - // The limit clears once everything currently counted has aged out of the window. - // Derived from the current bucket boundary plus the full window, so the estimate - // does not drift with sub-bucket remainder. - const std::int64_t window_ms = - static_cast(m_bucket_count) * m_config.seconds_per_bucket * 1000; - m_resolves_at_ms = m_last_bucket_change_ms + window_ms; - return false; - } - - return true; + return !WouldTrip(); } void RateLimiter::Commit() @@ -179,26 +202,54 @@ void RateLimiter::Commit() if (!m_config.enabled || m_bucket_count <= 0) { return; } - m_buckets[static_cast(m_last_bucket)]++; - m_total++; - m_total_in_tripwire++; -} -bool RateLimiter::TryAcquire() -{ - if (!CanAcquire()) { - return false; + // Defensive: `Tick` initialises bucket 0, so this cannot happen through the executor. + // But writing to `m_buckets[-1]` is a stack overrun rather than a wrong number, so the + // guard is worth the branch. + if (!m_started.load(std::memory_order_relaxed)) { + return; + } + + // The window has drained, so the limit is lifted. `IsLimited()` derives from `m_total` + // as well, so this is belt-and-braces rather than the only place it clears. + if (m_limited.load(std::memory_order_relaxed) + && m_total.load(std::memory_order_relaxed) <= 0) { + m_limited.store(false, std::memory_order_relaxed); + m_ms_until_clear.store(0, std::memory_order_relaxed); + } + + const int last_bucket = m_last_bucket.load(std::memory_order_relaxed); + m_buckets[static_cast(last_bucket)].fetch_add(1, std::memory_order_relaxed); + m_total.fetch_add(1, std::memory_order_relaxed); + m_total_in_tripwire.fetch_add(1, std::memory_order_relaxed); + + // `IsLimited()` reports whether the *next* request would be refused, which is what + // `CanAcquire()` will say. Recording it here keeps the two in agreement: without this, + // `CanAcquire()` would refuse while `IsLimited()` still said false. + // + // The request that *reaches* the cap is allowed - the cap is "more than 280", not "280" - + // so this is `WouldTrip()` after the increment, not before it. + if (WouldTrip()) { + m_limited.store(true, std::memory_order_relaxed); + + // The limit clears once everything currently counted has aged out of the window, + // plus whatever is left of the current bucket. + const std::int64_t window_ms = + static_cast(m_bucket_count) * m_config.seconds_per_bucket * 1000; + const std::int64_t bucket_ms = + static_cast(m_config.seconds_per_bucket) * 1000; + m_ms_until_clear.store( + window_ms + (bucket_ms - m_ms_into_bucket.load(std::memory_order_relaxed)), + std::memory_order_relaxed); } - Commit(); - return true; } int RateLimiter::SecondsUntilClear() const { - if (!m_limited) { + if (!IsLimited()) { return 0; } - const std::int64_t remaining = m_resolves_at_ms - m_clock.NowMs(); + const std::int64_t remaining = m_ms_until_clear.load(std::memory_order_relaxed); if (remaining <= 0) { return 0; } @@ -208,4 +259,4 @@ int RateLimiter::SecondsUntilClear() const } } // namespace core -} // namespace lootlocker +} // namespace lootlocker \ No newline at end of file diff --git a/src/core/rate_limiter.h b/src/core/rate_limiter.h index 1b9e87f..1f600e8 100644 --- a/src/core/rate_limiter.h +++ b/src/core/rate_limiter.h @@ -25,6 +25,8 @@ #include "clock.h" +#include +#include #include #include @@ -38,25 +40,36 @@ class RateLimiter { RateLimiter(const RateLimiter&) = delete; RateLimiter& operator=(const RateLimiter&) = delete; - // Whether a request may be sent now. Does not record anything. + // Advances the window by `delta_ms`. Called by the executor's tick, once per `Update()`, + // before anything is promoted. + // + // **Time is pushed in, not read here.** The limiter used to call the clock itself from + // inside `CanAcquire()`, which made a `const`-looking predicate mutate the whole module - + // and meant the window only advanced when someone happened to ask. A tickable component + // should be told how much time passed and do nothing else; the executor owns the clock + // and is the one place that reads it. + void Tick(std::int64_t delta_ms); + + // Whether a request may be sent now. **Const**: it reads the window and reports, and + // does not advance or record anything. // // Split from `Commit` so the executor can check *before* starting a transfer and record // only if the transfer actually started. `IHttpTransport::Start` may return 0, and a // start that failed sent nothing - counting it would burn quota for a request that never // left, and repeated failures could hold unrelated queued requests. - bool CanAcquire(); + bool CanAcquire() const; + // Records one request against the window. Call only after `CanAcquire()` returned true // and the transfer actually started. void Commit(); - // Records one request and returns true when it may be sent now. - // - // Convenience for a caller that has nothing between the check and the send. The executor - // does not use it, because it has a `Start` call in between. - bool TryAcquire(); - // True while the limiter is holding requests back. - bool IsLimited() const { return m_limited; } + // + // Derived rather than stored: a stored flag has to be cleared by something, and the only + // method that runs after a successful check is `Commit` - so a caller that only ever + // checked would see a stale `true` for ever. Deriving it means `IsLimited()` and + // `CanAcquire()` cannot disagree. + bool IsLimited() const { return m_limited && m_total > 0; } // Seconds until the limit is expected to clear. 0 when not limited. // @@ -74,11 +87,12 @@ class RateLimiter { void Reset(); private: - // Advances the bucket pointer to reflect elapsed time, zeroing the buckets that have - // slid out of the window and removing their counts from the running totals. - void Advance(std::int64_t now_ms); + // Zeroes the buckets that have slid out of the window and removes their counts from the + // running totals. + void SlideWindow(std::int64_t delta_ms); - // Whether adding one more request would exceed either threshold. + // Whether adding one more request would exceed either threshold. Used by `CanAcquire()` + // before anything is recorded, and by `Commit()` after, so the two agree. bool WouldTrip() const; RateLimitConfig m_config; @@ -90,24 +104,45 @@ class RateLimiter { int m_buckets_per_tripwire = 0; int m_per_bucket_limit = 0; - std::vector m_buckets; - - // Index of the most recently written bucket. -1 before the first request. - int m_last_bucket = -1; - - // When the current bucket became active, snapped to a bucket boundary so sub-bucket - // remainder cannot accumulate as drift. - std::int64_t m_last_bucket_change_ms = 0; - bool m_started = false; + // **Atomics, because the SDK is single-threaded by contract but not by enforcement.** + // `Update()` is documented as the only entry point and callbacks fire on the calling + // thread (D5), so in a correct program nothing here is contended. But a game that calls + // `Update()` from two threads by mistake would otherwise corrupt the window silently, + // and a torn read of `m_total` is a wrong rate limit rather than a crash - the kind of + // bug that shows up as "the limiter randomly trips" months later. + // + // Relaxed ordering throughout: the requirement is that each field is read and written + // atomically, not that other threads observe any particular order between them. A + // stronger order would buy nothing here and cost on the hot path. + // + // Explicit locks are deliberately not used. There is no invariant that spans two fields + // - a torn read of `m_total` against `m_total_in_tripwire` gives a slightly stale + // decision, not a corrupt one - so a mutex would add contention to buy nothing. + // A heap array rather than a `std::vector`: `std::atomic` is neither copyable nor + // movable, so a vector cannot grow or reallocate. The size is fixed at construction, so + // an array is the right shape anyway. + std::unique_ptr[]> m_buckets; + + // Index of the most recently written bucket. -1 before the first tick. + std::atomic m_last_bucket{-1}; + + // Milliseconds accumulated since the current bucket became active. Kept as a remainder + // rather than an absolute timestamp, because the limiter is told deltas and never reads + // the clock: sub-bucket remainder carries forward, so it cannot accumulate as drift. + std::atomic m_ms_into_bucket{0}; + std::atomic m_started{false}; // Requests across every bucket in the array. - int m_total = 0; + std::atomic m_total{0}; // Requests in the buckets that fall inside the current tripwire window. - int m_total_in_tripwire = 0; + std::atomic m_total_in_tripwire{0}; + + std::atomic m_limited{false}; - bool m_limited = false; - std::int64_t m_resolves_at_ms = 0; + // Milliseconds until the limit is expected to clear, counted down by `Tick`. A remaining + // duration rather than a deadline, for the same reason: no clock reads. + std::atomic m_ms_until_clear{0}; }; } // namespace core diff --git a/tests/test_executor.cpp b/tests/test_executor.cpp index 7b24da5..2d0f3c9 100644 --- a/tests/test_executor.cpp +++ b/tests/test_executor.cpp @@ -87,7 +87,12 @@ struct Fixture { explicit Fixture(QueueConfig config = DefaultQueue()) : transport(std::make_shared()), logger(std::make_shared()) { - executor.reset(new Executor(config, transport, clock, logger)); + ExecutorSettings settings; + settings.queue = config; + settings.transport = transport; + settings.clock = &clock; + settings.logger = logger; + executor.reset(new Executor(settings)); } std::shared_ptr transport; @@ -652,7 +657,13 @@ void TestInvalidConfigRejectsThroughUpdate() auto transport = std::make_shared(); auto logger = std::make_shared(); FakeClock clock; - Executor executor(DefaultQueue(), transport, clock, logger, config_error); + ExecutorSettings settings; + settings.queue = DefaultQueue(); + settings.transport = transport; + settings.clock = &clock; + settings.logger = logger; + settings.config_error = config_error; + Executor executor(settings); int delivered = 0; Completion last; @@ -1025,7 +1036,13 @@ struct LimitedFixture { limit.moving_average_fraction = 1.0; limit.moving_average_time_frames = 1; - executor.reset(new Executor(queue, limit, transport, clock, logger, Error())); + ExecutorSettings settings; + settings.queue = queue; + settings.rate_limit = limit; + settings.transport = transport; + settings.clock = &clock; + settings.logger = logger; + executor.reset(new Executor(settings)); } std::shared_ptr transport; @@ -1088,7 +1105,13 @@ void TestServerRateLimitIsHandledByRetryNotTheLimiter() auto transport = std::make_shared(); auto logger = std::make_shared(); FakeClock clock; - Executor executor(queue, limit, transport, clock, logger, Error()); + ExecutorSettings settings; + settings.queue = queue; + settings.rate_limit = limit; + settings.transport = transport; + settings.clock = &clock; + settings.logger = logger; + Executor executor(settings); int delivered = 0; Completion last; @@ -1153,7 +1176,13 @@ void TestFailedStartDoesNotBurnQuota() auto transport = std::make_shared(); auto logger = std::make_shared(); FakeClock clock; - Executor executor(queue, limit, transport, clock, logger, Error()); + ExecutorSettings settings; + settings.queue = queue; + settings.rate_limit = limit; + settings.transport = transport; + settings.clock = &clock; + settings.logger = logger; + Executor executor(settings); int delivered = 0; for (int i = 0; i < 10; ++i) { diff --git a/tests/test_rate_limiter.cpp b/tests/test_rate_limiter.cpp index ef50be9..01e5351 100644 --- a/tests/test_rate_limiter.cpp +++ b/tests/test_rate_limiter.cpp @@ -27,6 +27,29 @@ class FakeClock : public Clock { std::int64_t m_now = 1000000; // non-zero, so "not set" is distinguishable }; +// The limiter is told deltas and never reads the clock, so a test drives it by ticking. +// +// `Acquire` is the old `TryAcquire` shape - tick, check, commit - which is what the executor +// does across an `Update()`. Keeping it here rather than in the limiter is deliberate: the +// limiter has no business deciding when time passes. +bool Acquire(RateLimiter& limiter, FakeClock& clock, std::int64_t delta_ms = 0) +{ + clock.Advance(delta_ms); + limiter.Tick(delta_ms); + if (!limiter.CanAcquire()) { + return false; + } + limiter.Commit(); + return true; +} + +void Advance(RateLimiter& limiter, FakeClock& clock, int seconds) +{ + const std::int64_t delta_ms = static_cast(seconds) * 1000; + clock.Advance(delta_ms); + limiter.Tick(delta_ms); +} + RateLimitConfig Defaults() { RateLimitConfig config; @@ -59,15 +82,18 @@ void TestBurstTripsTheTripwire() // 280 requests in one bucket is allowed: the cap is "more than 280". int allowed = 0; for (int i = 0; i < 280; ++i) { - if (limiter.TryAcquire()) { + if (Acquire(limiter, clock)) { ++allowed; } } CHECK_EQ_INT(allowed, 280); - CHECK(!limiter.IsLimited()); - // The 281st trips it. - CHECK(!limiter.TryAcquire()); + // `IsLimited()` reports whether the *next* request would be refused, so it is already + // true here - the 281st is the one that trips. + CHECK(limiter.IsLimited()); + + // The 281st is refused. + CHECK(!Acquire(limiter, clock)); CHECK(limiter.IsLimited()); CHECK_EQ_INT(limiter.TripwireCount(), 280); } @@ -78,9 +104,9 @@ void TestTripwireClearsWhenTheWindowSlides() RateLimiter limiter(Defaults(), clock); for (int i = 0; i < 280; ++i) { - CHECK(limiter.TryAcquire()); + CHECK(Acquire(limiter, clock)); } - CHECK(!limiter.TryAcquire()); + CHECK(!Acquire(limiter, clock)); CHECK(limiter.IsLimited()); // The tripwire window is 60 s, but the limiter does not clear when the tripwire window @@ -89,17 +115,17 @@ void TestTripwireClearsWhenTheWindowSlides() // the Unreal and Unity SDKs, and it is deliberately conservative: a burst that tripped // the hard cap backs the client off for the full window rather than resuming the // instant the 60 s count drops. - clock.AdvanceSeconds(59); - CHECK(!limiter.TryAcquire()); + Advance(limiter, clock, 59); + CHECK(!Acquire(limiter, clock)); CHECK(limiter.IsLimited()); - clock.AdvanceSeconds(60); - CHECK(!limiter.TryAcquire()); + Advance(limiter, clock, 60); + CHECK(!Acquire(limiter, clock)); CHECK(limiter.IsLimited()); // Past the full window, the counted requests have aged out and the limiter clears. - clock.AdvanceSeconds(62); - CHECK(limiter.TryAcquire()); + Advance(limiter, clock, 62); + CHECK(limiter.CanAcquire()); CHECK(!limiter.IsLimited()); } @@ -117,9 +143,9 @@ void TestSustainedTrafficTripsTheMovingAverage() // soft cap. for (int bucket = 0; bucket < 36; ++bucket) { for (int i = 0; i < 18; ++i) { - CHECK(limiter.TryAcquire()); + CHECK(Acquire(limiter, clock)); } - clock.AdvanceSeconds(5); + Advance(limiter, clock, 5); } CHECK(!limiter.IsLimited()); @@ -127,13 +153,13 @@ void TestSustainedTrafficTripsTheMovingAverage() // the tripwire (280 per 60 s) is nowhere near. for (int bucket = 0; bucket < 36; ++bucket) { for (int i = 0; i < 19; ++i) { - if (!limiter.TryAcquire()) { + if (!Acquire(limiter, clock)) { // Tripped partway through, which is the expected outcome. CHECK(limiter.IsLimited()); return; } } - clock.AdvanceSeconds(5); + Advance(limiter, clock, 5); } // Reaching here means it never tripped, which is the failure. @@ -150,12 +176,12 @@ void TestMovingAverageTripsBelowTheTripwire() bool tripped = false; for (int bucket = 0; bucket < 36 && !tripped; ++bucket) { for (int i = 0; i < 19; ++i) { - if (!limiter.TryAcquire()) { + if (!Acquire(limiter, clock)) { tripped = true; break; } } - clock.AdvanceSeconds(5); + Advance(limiter, clock, 5); } CHECK(tripped); @@ -173,22 +199,22 @@ void TestHeldRequestsAreNotCounted() RateLimiter limiter(Defaults(), clock); for (int i = 0; i < 280; ++i) { - CHECK(limiter.TryAcquire()); + CHECK(Acquire(limiter, clock)); } - CHECK(!limiter.TryAcquire()); + CHECK(!Acquire(limiter, clock)); CHECK_EQ_INT(limiter.TripwireCount(), 280); // A held request must not count against the window, or the limiter would keep itself // tripped by its own backlog and the window would never drain. for (int i = 0; i < 100; ++i) { - CHECK(!limiter.TryAcquire()); + CHECK(!Acquire(limiter, clock)); } CHECK_EQ_INT(limiter.TripwireCount(), 280); // So it still clears on schedule - the full moving-average window, not the tripwire // window. - clock.AdvanceSeconds(181); - CHECK(limiter.TryAcquire()); + Advance(limiter, clock, 181); + CHECK(Acquire(limiter, clock)); } void TestSecondsUntilClearIsAnEstimateThatExpires() @@ -199,18 +225,19 @@ void TestSecondsUntilClearIsAnEstimateThatExpires() CHECK_EQ_INT(limiter.SecondsUntilClear(), 0); for (int i = 0; i < 280; ++i) { - CHECK(limiter.TryAcquire()); + CHECK(Acquire(limiter, clock)); } - CHECK(!limiter.TryAcquire()); + CHECK(!Acquire(limiter, clock)); - // The window is 3 minutes (36 buckets of 5 s), so the estimate is bounded by that. + // The window is 3 minutes (36 buckets of 5 s), plus whatever is left of the current + // bucket - so the estimate is bounded by 180 s plus one bucket. const int estimate = limiter.SecondsUntilClear(); CHECK(estimate > 0); - CHECK(estimate <= 180); + CHECK(estimate <= 185); // Waiting the estimate out clears it. - clock.AdvanceSeconds(estimate); - CHECK(limiter.TryAcquire()); + Advance(limiter, clock, estimate); + CHECK(Acquire(limiter, clock)); CHECK_EQ_INT(limiter.SecondsUntilClear(), 0); } @@ -226,7 +253,7 @@ void TestDisabledLimiterAlwaysAllows() // Far past every threshold, and still allowed. for (int i = 0; i < 10000; ++i) { - CHECK(limiter.TryAcquire()); + CHECK(Acquire(limiter, clock)); } CHECK(!limiter.IsLimited()); } @@ -237,9 +264,9 @@ void TestResetClearsEverything() RateLimiter limiter(Defaults(), clock); for (int i = 0; i < 280; ++i) { - CHECK(limiter.TryAcquire()); + CHECK(Acquire(limiter, clock)); } - CHECK(!limiter.TryAcquire()); + CHECK(!Acquire(limiter, clock)); CHECK(limiter.IsLimited()); limiter.Reset(); @@ -247,7 +274,7 @@ void TestResetClearsEverything() CHECK(!limiter.IsLimited()); CHECK_EQ_INT(limiter.TripwireCount(), 0); CHECK_EQ_INT(limiter.WindowCount(), 0); - CHECK(limiter.TryAcquire()); + CHECK(Acquire(limiter, clock)); } void TestLongIdlePeriodClearsWithoutIterating() @@ -256,16 +283,16 @@ void TestLongIdlePeriodClearsWithoutIterating() RateLimiter limiter(Defaults(), clock); for (int i = 0; i < 280; ++i) { - CHECK(limiter.TryAcquire()); + CHECK(Acquire(limiter, clock)); } - CHECK(!limiter.TryAcquire()); + CHECK(!Acquire(limiter, clock)); // A day of idleness is far more buckets than exist. The limiter must clear rather than // loop over a window that is entirely stale. - clock.AdvanceSeconds(86400); - CHECK(limiter.TryAcquire()); + Advance(limiter, clock, 86400); + CHECK(limiter.CanAcquire()); CHECK(!limiter.IsLimited()); - CHECK_EQ_INT(limiter.TripwireCount(), 1); + CHECK_EQ_INT(limiter.TripwireCount(), 0); } void TestCustomConstantsAreHonoured() @@ -284,15 +311,15 @@ void TestCustomConstantsAreHonoured() int allowed = 0; for (int i = 0; i < 10; ++i) { - if (limiter.TryAcquire()) { + if (Acquire(limiter, clock)) { ++allowed; } } CHECK_EQ_INT(allowed, 10); - CHECK(!limiter.TryAcquire()); + CHECK(!Acquire(limiter, clock)); - clock.AdvanceSeconds(11); - CHECK(limiter.TryAcquire()); + Advance(limiter, clock, 11); + CHECK(Acquire(limiter, clock)); } void TestNonDivisiblePolicyIsRejected() @@ -309,7 +336,7 @@ void TestNonDivisiblePolicyIsRejected() // Rejected means the limiter is inert rather than silently misconfigured. It allows // everything, which is the safe direction: a broken policy must not throttle a game. for (int i = 0; i < 1000; ++i) { - CHECK(limiter.TryAcquire()); + CHECK(Acquire(limiter, clock)); } CHECK(!limiter.IsLimited()); } @@ -329,7 +356,7 @@ void TestOverflowingBucketCountIsRejected() // Inert rather than negative, and no huge allocation. for (int i = 0; i < 1000; ++i) { - CHECK(limiter.TryAcquire()); + CHECK(Acquire(limiter, clock)); } CHECK(!limiter.IsLimited()); } @@ -340,6 +367,10 @@ void TestCommitIsSeparateFromTheCheck() FakeClock clock; RateLimiter limiter(Defaults(), clock); + // The first tick initialises bucket 0. Without it `Commit` has nowhere to write, which is + // why the executor ticks before promoting anything. + limiter.Tick(0); + CHECK(limiter.CanAcquire()); CHECK_EQ_INT(limiter.TripwireCount(), 0); // checking alone records nothing From 7d7c35ca9d752885631821703c1af08332f1dcae Mon Sep 17 00:00:00 2001 From: Erik Bylund Date: Tue, 24 Nov 2026 15:52:59 +0100 Subject: [PATCH 4/5] Validate the rate-limit policy, and stop using 0 as a tick sentinel Four review comments, two of them real bugs. - ValidateConfig never rejected a non-divisible window or an unbounded bucket count, so a Client built with 60 s / 7 s buckets was considered valid and the limiter silently became inert - unlimited traffic, with nothing to say so. Both are now rejected at validation, where the adopter sees them, rather than degrading at construction. The bucket count is bounded at 100000: the defaults derive 36, and even a 1-hour window with 1 s buckets over 3 frames is 10,800, so anything past that is a typo. - The executor used 0 as its "no previous tick" sentinel, but Clock only promises monotonic milliseconds, not a non-zero origin. A clock that legitimately started at 0 left m_last_tick_ms at 0 for ever and computed a delta of 0 every time, so the limiter's buckets never advanced and held requests stayed blocked indefinitely. Initialisation is now a separate bool. - A disabled limiter derives and allocates nothing. Deriving first and guarding the allocation afterwards still attempted the allocation for a disabled policy with a huge window, which in a no-exceptions build terminates the client. - Formatting: kRelaxed names the memory order once instead of forty times, and the accessors use implicit conversion where the ordering does not matter. Explicit .load()/.store() is kept only where it does - the fetch_add in Commit, which is the one place the read-modify-write matters. Both bugs verified by sabotage: restoring the 0 sentinel leaves the held requests stuck at 3 of 5, and removing the divisibility check fails three assertions. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/core/config.cpp | 27 +++++++++ src/core/executor.cpp | 11 +++- src/core/executor.h | 1 + src/core/rate_limiter.cpp | 113 ++++++++++++++++++------------------ src/core/rate_limiter.h | 10 ++++ tests/test_executor.cpp | 63 ++++++++++++++++++++ tests/test_rate_limiter.cpp | 53 ++++++++++++----- 7 files changed, 207 insertions(+), 71 deletions(-) diff --git a/src/core/config.cpp b/src/core/config.cpp index 1767e02..d95bd10 100644 --- a/src/core/config.cpp +++ b/src/core/config.cpp @@ -221,6 +221,33 @@ Error ValidateConfig(const Config& config) return Invalid("rate_limit.moving_average_time_frames must be positive"); } + // The window must divide evenly into buckets. A non-divisible policy silently + // shortens the window - 60 s with 7 s buckets becomes an effective 56 s tripwire and + // a 168 s moving average - so the adopter gets a different rate limit than they + // asked for, with nothing to say so. + if (config.rate_limit.tripwire_window_seconds % config.rate_limit.seconds_per_bucket + != 0) { + return Invalid("rate_limit.tripwire_window_seconds must be a multiple of " + "seconds_per_bucket"); + } + + // The derived bucket count must be bounded, because it is an allocation. Without + // this, a large window with 1 s buckets asks for billions of buckets - gigabytes of + // atomics - and in a no-exceptions build that terminates the client during + // construction. + // + // The bound is generous: the defaults derive 36, and even a 1-hour window with 1 s + // buckets over 3 frames is 10,800. Anything past this is a typo rather than a policy. + const long long buckets_per_tripwire = + config.rate_limit.tripwire_window_seconds / config.rate_limit.seconds_per_bucket; + const long long bucket_count = + buckets_per_tripwire * config.rate_limit.moving_average_time_frames; + if (bucket_count > 100000) { + return Invalid("rate_limit settings derive " + std::to_string(bucket_count) + + " buckets, which exceeds the limit of 100000; raise " + "seconds_per_bucket or lower moving_average_time_frames"); + } + // The fraction must be finite and in (0, 1]. A NaN or an out-of-range value would // make PerBucketLimit() produce a nonsense threshold. const double f = config.rate_limit.moving_average_fraction; diff --git a/src/core/executor.cpp b/src/core/executor.cpp index 43521c1..2e95dfe 100644 --- a/src/core/executor.cpp +++ b/src/core/executor.cpp @@ -348,7 +348,16 @@ bool Executor::Update() // The executor is the one place that reads the clock, and it pushes the delta into every // tickable component. A component that read the clock itself would advance only when // someone happened to ask it something, which is how the limiter used to work. - const std::int64_t delta_ms = (m_last_tick_ms == 0) ? 0 : now - m_last_tick_ms; + // + // Initialisation is tracked separately from the timestamp. `Clock` only promises + // monotonic milliseconds, not a non-zero origin, so a clock that legitimately starts at 0 + // would otherwise leave `m_last_tick_ms` at 0 for ever and compute a delta of 0 every + // time - the limiter's buckets would never advance and held requests would stay blocked. + std::int64_t delta_ms = 0; + if (m_has_ticked) { + delta_ms = now - m_last_tick_ms; + } + m_has_ticked = true; m_last_tick_ms = now; m_rate_limiter.Tick(delta_ms); diff --git a/src/core/executor.h b/src/core/executor.h index aa3bb38..e0eb1d6 100644 --- a/src/core/executor.h +++ b/src/core/executor.h @@ -194,6 +194,7 @@ class Executor { std::weak_ptr m_logger; std::int64_t m_last_tick_ms = 0; + bool m_has_ticked = false; // The client-side throttle (D25). Held by value: it is small, it is ticked by `Update()`, // and it has no reason to outlive the executor. diff --git a/src/core/rate_limiter.cpp b/src/core/rate_limiter.cpp index 251f922..79d8b30 100644 --- a/src/core/rate_limiter.cpp +++ b/src/core/rate_limiter.cpp @@ -50,6 +50,13 @@ int DeriveBucketCount(const RateLimitConfig& config) RateLimiter::RateLimiter(const RateLimitConfig& config, Clock& clock) : m_config(config), m_clock(clock) { + // A disabled limiter derives and allocates nothing. Deriving first and guarding the + // allocation afterwards would still attempt the allocation for a disabled policy with a + // huge window, which in a no-exceptions build terminates the client. + if (!config.enabled) { + return; + } + m_bucket_count = DeriveBucketCount(config); if (m_bucket_count > 0) { m_buckets_per_tripwire = config.tripwire_window_seconds / config.seconds_per_bucket; @@ -59,23 +66,23 @@ RateLimiter::RateLimiter(const RateLimitConfig& config, Clock& clock) // so a vector cannot hold it. m_buckets.reset(new std::atomic[static_cast(m_bucket_count)]); for (int i = 0; i < m_bucket_count; ++i) { - m_buckets[static_cast(i)].store(0, std::memory_order_relaxed); + m_buckets[static_cast(i)] = 0; } } } void RateLimiter::Reset() { - for (int i = 0; i < m_bucket_count; ++i) { - m_buckets[static_cast(i)].store(0, std::memory_order_relaxed); - } - m_last_bucket.store(-1, std::memory_order_relaxed); - m_ms_into_bucket.store(0, std::memory_order_relaxed); - m_started.store(false, std::memory_order_relaxed); - m_total.store(0, std::memory_order_relaxed); - m_total_in_tripwire.store(0, std::memory_order_relaxed); - m_limited.store(false, std::memory_order_relaxed); - m_ms_until_clear.store(0, std::memory_order_relaxed); + for (int i = 0; i < m_bucket_count; ++i) { + m_buckets[static_cast(i)] = 0; + } + m_last_bucket = -1; + m_ms_into_bucket = 0; + m_started = false; + m_total = 0; + m_total_in_tripwire = 0; + m_limited = false; + m_ms_until_clear = 0; } void RateLimiter::Tick(std::int64_t delta_ms) @@ -86,10 +93,10 @@ void RateLimiter::Tick(std::int64_t delta_ms) // The first tick initialises bucket 0, even with a zero delta. Without this the limiter // would stay unstarted until time actually passed, and `Commit` would write to bucket -1. - if (!m_started.load(std::memory_order_relaxed)) { - m_started.store(true, std::memory_order_relaxed); - m_last_bucket.store(0, std::memory_order_relaxed); - m_ms_into_bucket.store(0, std::memory_order_relaxed); + if (!m_started) { + m_started = true; + m_last_bucket = 0; + m_ms_into_bucket = 0; return; } @@ -99,12 +106,12 @@ void RateLimiter::Tick(std::int64_t delta_ms) // The countdown to clearing is a duration, so it simply decreases. Clamped at zero so a // long idle period cannot make it negative and then take a whole window to climb back. - if (m_limited.load(std::memory_order_relaxed)) { - std::int64_t remaining = m_ms_until_clear.load(std::memory_order_relaxed) - delta_ms; + if (m_limited) { + std::int64_t remaining = m_ms_until_clear - delta_ms; if (remaining < 0) { remaining = 0; } - m_ms_until_clear.store(remaining, std::memory_order_relaxed); + m_ms_until_clear = remaining; } SlideWindow(delta_ms); @@ -114,37 +121,34 @@ void RateLimiter::SlideWindow(std::int64_t delta_ms) { const std::int64_t bucket_ms = static_cast(m_config.seconds_per_bucket) * 1000; - const std::int64_t ms_into_bucket = - m_ms_into_bucket.load(std::memory_order_relaxed) + delta_ms; + const std::int64_t ms_into_bucket = m_ms_into_bucket + delta_ms; const std::int64_t numberOfBucketsTraversed = ms_into_bucket / bucket_ms; if (numberOfBucketsTraversed == 0) { - m_ms_into_bucket.store(ms_into_bucket, std::memory_order_relaxed); + m_ms_into_bucket = ms_into_bucket; return; } // Keep only the remainder, so sub-bucket time carries forward and cannot accumulate as // drift over a long run. - m_ms_into_bucket.store(ms_into_bucket - numberOfBucketsTraversed * bucket_ms, - std::memory_order_relaxed); + m_ms_into_bucket = ms_into_bucket - numberOfBucketsTraversed * bucket_ms; - const int last_bucket = m_last_bucket.load(std::memory_order_relaxed); + const int last_bucket = m_last_bucket; // More buckets elapsed than exist: everything has aged out, so clear rather than looping // over a window that is entirely stale. if (numberOfBucketsTraversed >= m_bucket_count) { for (int i = 0; i < m_bucket_count; ++i) { - m_buckets[static_cast(i)].store(0, std::memory_order_relaxed); + m_buckets[static_cast(i)] = 0; } - m_total.store(0, std::memory_order_relaxed); - m_total_in_tripwire.store(0, std::memory_order_relaxed); - m_last_bucket.store(static_cast(numberOfBucketsTraversed % m_bucket_count), - std::memory_order_relaxed); + m_total = 0; + m_total_in_tripwire = 0; + m_last_bucket = static_cast(numberOfBucketsTraversed % m_bucket_count); return; } - int total = m_total.load(std::memory_order_relaxed); - int total_in_tripwire = m_total_in_tripwire.load(std::memory_order_relaxed); + int total = m_total; + int total_in_tripwire = m_total_in_tripwire; for (std::int64_t step = 1; step <= numberOfBucketsTraversed; ++step) { const int bucket = static_cast((last_bucket + step) % m_bucket_count); @@ -156,29 +160,27 @@ void RateLimiter::SlideWindow(std::int64_t delta_ms) leaving_tripwire += m_bucket_count; } - total_in_tripwire -= m_buckets[static_cast(leaving_tripwire)].load( - std::memory_order_relaxed); - total -= m_buckets[static_cast(bucket)].load(std::memory_order_relaxed); - m_buckets[static_cast(bucket)].store(0, std::memory_order_relaxed); + total_in_tripwire -= m_buckets[static_cast(leaving_tripwire)]; + total -= m_buckets[static_cast(bucket)]; + m_buckets[static_cast(bucket)] = 0; } - m_total.store(total, std::memory_order_relaxed); - m_total_in_tripwire.store(total_in_tripwire, std::memory_order_relaxed); - m_last_bucket.store(static_cast((last_bucket + numberOfBucketsTraversed) % m_bucket_count), - std::memory_order_relaxed); + m_total = total; + m_total_in_tripwire = total_in_tripwire; + m_last_bucket = static_cast((last_bucket + numberOfBucketsTraversed) % m_bucket_count); } bool RateLimiter::WouldTrip() const { // Tripwire: this request would take the window to the cap. - if (m_total_in_tripwire.load(std::memory_order_relaxed) + 1 + if (m_total_in_tripwire + 1 > m_config.max_requests_per_tripwire) { return true; } // Moving average: the per-bucket average across the whole window would exceed the // derived limit. Integer division, matching the reference implementations. - const int projected = m_total.load(std::memory_order_relaxed) + 1; + const int projected = m_total + 1; return (projected / m_bucket_count) > m_per_bucket_limit; } @@ -190,8 +192,8 @@ bool RateLimiter::CanAcquire() const // While limited, nothing is counted. A held request has not been sent, so counting it // would keep the limiter tripped by its own backlog - the window would never drain. - if (m_limited.load(std::memory_order_relaxed)) { - return m_total.load(std::memory_order_relaxed) <= 0; + if (m_limited) { + return m_total <= 0; } return !WouldTrip(); @@ -206,22 +208,21 @@ void RateLimiter::Commit() // Defensive: `Tick` initialises bucket 0, so this cannot happen through the executor. // But writing to `m_buckets[-1]` is a stack overrun rather than a wrong number, so the // guard is worth the branch. - if (!m_started.load(std::memory_order_relaxed)) { + if (!m_started) { return; } // The window has drained, so the limit is lifted. `IsLimited()` derives from `m_total` // as well, so this is belt-and-braces rather than the only place it clears. - if (m_limited.load(std::memory_order_relaxed) - && m_total.load(std::memory_order_relaxed) <= 0) { - m_limited.store(false, std::memory_order_relaxed); - m_ms_until_clear.store(0, std::memory_order_relaxed); + if (m_limited && m_total <= 0) { + m_limited = false; + m_ms_until_clear = 0; } - const int last_bucket = m_last_bucket.load(std::memory_order_relaxed); - m_buckets[static_cast(last_bucket)].fetch_add(1, std::memory_order_relaxed); - m_total.fetch_add(1, std::memory_order_relaxed); - m_total_in_tripwire.fetch_add(1, std::memory_order_relaxed); + const int last_bucket = m_last_bucket; + m_buckets[static_cast(last_bucket)].fetch_add(1, kRelaxed); + m_total.fetch_add(1, kRelaxed); + m_total_in_tripwire.fetch_add(1, kRelaxed); // `IsLimited()` reports whether the *next* request would be refused, which is what // `CanAcquire()` will say. Recording it here keeps the two in agreement: without this, @@ -230,7 +231,7 @@ void RateLimiter::Commit() // The request that *reaches* the cap is allowed - the cap is "more than 280", not "280" - // so this is `WouldTrip()` after the increment, not before it. if (WouldTrip()) { - m_limited.store(true, std::memory_order_relaxed); + m_limited = true; // The limit clears once everything currently counted has aged out of the window, // plus whatever is left of the current bucket. @@ -238,9 +239,7 @@ void RateLimiter::Commit() static_cast(m_bucket_count) * m_config.seconds_per_bucket * 1000; const std::int64_t bucket_ms = static_cast(m_config.seconds_per_bucket) * 1000; - m_ms_until_clear.store( - window_ms + (bucket_ms - m_ms_into_bucket.load(std::memory_order_relaxed)), - std::memory_order_relaxed); + m_ms_until_clear = window_ms + (bucket_ms - m_ms_into_bucket); } } @@ -249,7 +248,7 @@ int RateLimiter::SecondsUntilClear() const if (!IsLimited()) { return 0; } - const std::int64_t remaining = m_ms_until_clear.load(std::memory_order_relaxed); + const std::int64_t remaining = m_ms_until_clear; if (remaining <= 0) { return 0; } diff --git a/src/core/rate_limiter.h b/src/core/rate_limiter.h index 1f600e8..358cc26 100644 --- a/src/core/rate_limiter.h +++ b/src/core/rate_limiter.h @@ -33,6 +33,16 @@ namespace lootlocker { namespace core { +// The memory order used throughout the limiter. +// +// Relaxed is deliberate: the requirement is that each field is read and written atomically, +// not that other threads observe any particular order between them. A stronger order would +// buy nothing here and cost on the hot path. +// +// Named once so the intent is stated in one place rather than repeated at every access, and +// so a future change to the ordering is one edit rather than forty. +constexpr std::memory_order kRelaxed = std::memory_order_relaxed; + class RateLimiter { public: RateLimiter(const RateLimitConfig& config, Clock& clock); diff --git a/tests/test_executor.cpp b/tests/test_executor.cpp index 2d0f3c9..43d9801 100644 --- a/tests/test_executor.cpp +++ b/tests/test_executor.cpp @@ -1195,6 +1195,68 @@ void TestFailedStartDoesNotBurnQuota() executor.Update(); CHECK_EQ_INT(delivered, 10); } +// A clock that starts at 0, which `Clock` permits: it only promises monotonic milliseconds, +// not a non-zero origin. +class ZeroOriginClock : public Clock { +public: + std::int64_t NowMs() override { return m_now; } + void Advance(std::int64_t ms) { m_now += ms; } + +private: + std::int64_t m_now = 0; +}; + +void TestZeroOriginClockStillAdvances() +{ + // The executor used 0 as its "no previous tick" sentinel, so a clock that legitimately + // started at 0 left `m_last_tick_ms` at 0 for ever and computed a delta of 0 every time - + // the limiter's buckets never advanced and held requests stayed blocked indefinitely. + QueueConfig queue = DefaultQueue(); + queue.max_retries = 0; + + RateLimitConfig limit; + limit.enabled = true; + limit.tripwire_window_seconds = 10; + limit.max_requests_per_tripwire = 3; + limit.seconds_per_bucket = 10; + limit.moving_average_fraction = 1.0; + limit.moving_average_time_frames = 1; + + auto transport = std::make_shared(); + auto logger = std::make_shared(); + ZeroOriginClock clock; + + ExecutorSettings settings; + settings.queue = queue; + settings.rate_limit = limit; + settings.transport = transport; + settings.clock = &clock; + settings.logger = logger; + Executor executor(settings); + + int delivered = 0; + for (int i = 0; i < 5; ++i) { + executor.Submit(Get("https://example.test/a" + std::to_string(i)), + [&delivered](const Completion&) { ++delivered; }); + } + + // Three go out, two are held. + CHECK(executor.Update()); + CHECK_EQ_INT(static_cast(transport->StartCount()), 3); + + for (const auto transfer : transport->Order()) { + transport->Complete(transfer, 200, "{}"); + } + executor.Update(); + CHECK_EQ_INT(delivered, 3); + + // The clock starts at 0, so this is the case that used to never advance. Past the window, + // the held two must be sent. + clock.Advance(11000); + CHECK(executor.Update()); + CHECK_EQ_INT(static_cast(transport->StartCount()), 5); +} + void TestAbandonCancelsInFlightWithoutCallingBack() { Fixture f; @@ -1256,6 +1318,7 @@ int main() TestTrippedRequestIsHeldThenDelivered(); TestServerRateLimitIsHandledByRetryNotTheLimiter(); TestFailedStartDoesNotBurnQuota(); + TestZeroOriginClockStillAdvances(); TestAbandonCancelsInFlightWithoutCallingBack(); return testing::Report(); diff --git a/tests/test_rate_limiter.cpp b/tests/test_rate_limiter.cpp index 01e5351..24a07f4 100644 --- a/tests/test_rate_limiter.cpp +++ b/tests/test_rate_limiter.cpp @@ -327,34 +327,60 @@ void TestNonDivisiblePolicyIsRejected() // 60 s with 7 s buckets does not divide. Silently shortening it would give an effective // 56 s tripwire and a 168 s moving average while the config still advertises 60/180 - // a different rate limit than the adopter asked for, with nothing to say so. + // + // Rejected at validation, not just at construction: a `Client` built from this config + // must fail rather than silently run unthrottled. RateLimitConfig config = Defaults(); config.seconds_per_bucket = 7; - FakeClock clock; - RateLimiter limiter(config, clock); + Config full; + full.domain_key = "1g9glch3"; + full.game_key = "prod_1c52468fc6e8420c955e3b6c303ea8cc"; + full.game_version = "1.2.1"; + full.rate_limit = config; - // Rejected means the limiter is inert rather than silently misconfigured. It allows - // everything, which is the safe direction: a broken policy must not throttle a game. - for (int i = 0; i < 1000; ++i) { - CHECK(Acquire(limiter, clock)); - } - CHECK(!limiter.IsLimited()); + const Error error = ValidateConfig(full); + CHECK(!error.Ok()); + CHECK(error.code == ErrorCode::InvalidConfig); + CHECK(error.message.find("multiple") != std::string::npos); } void TestOverflowingBucketCountIsRejected() { - // A large frame count with a large bucket count would overflow `int` on the multiply and - // wrap negative - and a negative bucket count takes the "disabled" fast path, silently - // turning the limiter off for a config that looked valid. + // A large window with 1 s buckets asks for billions of buckets - gigabytes of atomics - + // and in a no-exceptions build that terminates the client during construction. Rejected + // at validation so it cannot reach the allocator. + RateLimitConfig config = Defaults(); + config.tripwire_window_seconds = 2000000000; + config.seconds_per_bucket = 1; + config.moving_average_time_frames = 1; + + Config full; + full.domain_key = "1g9glch3"; + full.game_key = "prod_1c52468fc6e8420c955e3b6c303ea8cc"; + full.game_version = "1.2.1"; + full.rate_limit = config; + + const Error error = ValidateConfig(full); + CHECK(!error.Ok()); + CHECK(error.code == ErrorCode::InvalidConfig); + CHECK(error.message.find("buckets") != std::string::npos); +} + +void TestDisabledLimiterAllocatesNothing() +{ + // A disabled limiter must not derive or allocate a bucket array at all: the derivation + // happens before the allocation guard, so a disabled policy with a huge window would + // otherwise still try to allocate. RateLimitConfig config = Defaults(); + config.enabled = false; config.tripwire_window_seconds = 2000000000; config.seconds_per_bucket = 1; - config.moving_average_time_frames = 100; + config.moving_average_time_frames = 1; FakeClock clock; RateLimiter limiter(config, clock); - // Inert rather than negative, and no huge allocation. for (int i = 0; i < 1000; ++i) { CHECK(Acquire(limiter, clock)); } @@ -402,6 +428,7 @@ int main() TestCustomConstantsAreHonoured(); TestNonDivisiblePolicyIsRejected(); TestOverflowingBucketCountIsRejected(); + TestDisabledLimiterAllocatesNothing(); TestCommitIsSeparateFromTheCheck(); return testing::Report(); From 275fa28484d96c81971d85d64605431ea8d8c581 Mon Sep 17 00:00:00 2001 From: Erik Bylund Date: Tue, 24 Nov 2026 16:50:18 +0100 Subject: [PATCH 5/5] Do not build a limiter from a policy that failed validation ValidateConfig rejects an oversized rate-limit policy, but the client passed it straight to the executor anyway - so a rejected 2-billion-second window still derived 2 billion buckets and attempted an ~8 GiB allocation during Client construction. In a no-exceptions build that terminates the client, which defeats the point of validating. The client now disables the limiter when config_error is non-empty. The client is inert in that state anyway, so a disabled limiter is exactly right - and it means an invalid policy can never reach the allocator. This is the same class of bug as the previous round: validation rejecting something that construction then does anyway. Verified by sabotage - without the fix the test hangs trying to allocate 8 GiB rather than failing. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/core/client.cpp | 10 ++++++++++ tests/test_transport_e2e.cpp | 29 +++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/src/core/client.cpp b/src/core/client.cpp index ca21747..9ccb7af 100644 --- a/src/core/client.cpp +++ b/src/core/client.cpp @@ -79,7 +79,17 @@ Client::Client(const Config& config) : m_impl(new Impl()) core::ExecutorSettings settings; settings.queue = config.queue; + + // An invalid config means the policy was never validated, so it must not reach the + // limiter: a rejected 2-billion-second window would still derive 2 billion buckets and + // attempt a multi-gigabyte allocation during construction, which in a no-exceptions + // build terminates the client. The client is inert anyway, so a disabled limiter is + // exactly right. settings.rate_limit = config.rate_limit; + if (!m_impl->config_error.Ok()) { + settings.rate_limit.enabled = false; + } + settings.transport = transport; settings.clock = &m_impl->clock; settings.logger = logger; diff --git a/tests/test_transport_e2e.cpp b/tests/test_transport_e2e.cpp index 325ec03..712b35b 100644 --- a/tests/test_transport_e2e.cpp +++ b/tests/test_transport_e2e.cpp @@ -312,6 +312,34 @@ void TestInvalidConfigMakesTheClientInert() CHECK_EQ_INT(static_cast(fake->StartCount()), 0); } +void TestInvalidPolicyDoesNotAllocateInTheClient() +{ + // `ValidateConfig` rejects an oversized policy, but the client used to pass it straight + // to the executor anyway - so a rejected 2-billion-second window still derived 2 billion + // buckets and attempted a multi-gigabyte allocation during construction. In a + // no-exceptions build that terminates the client, which defeats the point of validating. + Config config; + config.domain_key = "1g9glch3"; + config.game_key = "prod_1c52468fc6e8420c955e3b6c303ea8cc"; + config.game_version = "1.2.1"; + config.rate_limit.tripwire_window_seconds = 2000000000; + config.rate_limit.seconds_per_bucket = 1; + config.rate_limit.moving_average_time_frames = 1; + + auto fake = std::make_shared(); + config.transport = fake; + + // The assertion is that this returns at all rather than exhausting memory. + Client client(config); + + CHECK(!client.ConfigError().Ok()); + CHECK(client.ConfigError().code == ErrorCode::InvalidConfig); + + // And it is inert, as an invalid client should be. + CHECK(!client.Update()); + CHECK_EQ_INT(static_cast(fake->StartCount()), 0); +} + } // namespace int main() @@ -319,6 +347,7 @@ int main() TestInjectedTransportIsUsedByTheClient(); TestSetTransportReplacesTheInjectedOne(); TestInvalidConfigMakesTheClientInert(); + TestInvalidPolicyDoesNotAllocateInTheClient(); #if defined(LOOTLOCKER_HAVE_CURL) TestRealRoundTripThroughCurl();