From ab6d3813b7fc176fbe55fbf6df9808c9d376de61 Mon Sep 17 00:00:00 2001 From: feruzm Date: Thu, 19 Nov 2026 13:07:51 +0000 Subject: [PATCH 1/4] Stop calling every rate-limited node; report upstream throttling as 503 RATELIMITED A 429 parks a node, but a parked node was still called as a last resort, so a pool that throttles this host cost one 429 per node per lookup. Ask at most one parked node per call (the soonest to lapse), and throw a distinct UpstreamRateLimitedException when 429s were the only failure. The SSR cache answers that case 503 with X-Ssr-Cache: RATELIMITED and a Retry-After, and counts it as rate_limited, so a consumer can tell upstream throttling from a broken proxy. Closes #123 --- .../EcencyApi.Tests/HiveRpcFailoverTests.cs | 72 +++++++++++++++++++ dotnet/EcencyApi.Tests/SsrRpcTests.cs | 35 +++++++++ .../EcencyApi/Handlers/PrivateApi.Recovery.cs | 1 + dotnet/EcencyApi/Handlers/SsrRpc.cs | 20 +++++- .../EcencyApi/Infrastructure/HiveRpcClient.cs | 58 ++++++++++++++- .../Infrastructure/NodeHealthTracker.cs | 32 ++++++++- 6 files changed, 211 insertions(+), 7 deletions(-) diff --git a/dotnet/EcencyApi.Tests/HiveRpcFailoverTests.cs b/dotnet/EcencyApi.Tests/HiveRpcFailoverTests.cs index 654cee9c..2db8c6ac 100644 --- a/dotnet/EcencyApi.Tests/HiveRpcFailoverTests.cs +++ b/dotnet/EcencyApi.Tests/HiveRpcFailoverTests.cs @@ -707,6 +707,78 @@ public async Task AllNodesMalformed_ThrowsNamingTheNode() Assert.Contains("http://127.0.0.1:", ex.Message); // node URL for diagnosability } + [Fact] + public async Task AWhollyThrottledPool_CostsOneUpstreamCallPerLookup() + { + // A 429 parks the node; calling every parked node anyway turns one lookup + // into one 429 per node while the whole pool is throttling us, which is + // exactly the load the park exists to shed. Within the parks, a lookup + // may probe ONE parked node, never all of them. + await using var a = new StubNode(() => 429); + await using var b = new StubNode(() => 429); + await using var c = new StubNode(() => 429); + long now = 0; + var client = new HiveRpcClient(new[] { a.Url, b.Url, c.Url }, timeoutMs: 500, failoverThreshold: 1, clock: () => now); + + await Assert.ThrowsAnyAsync(() => client.Call("condenser_api", "get_accounts", new JsonArray())); + Assert.Equal(3, a.Hits + b.Hits + c.Hits); // unparked at the start: each asked once + + now += 1_000; // well inside every park + await Assert.ThrowsAnyAsync(() => client.Call("condenser_api", "get_accounts", new JsonArray())); + Assert.Equal(4, a.Hits + b.Hits + c.Hits); + } + + [Fact] + public async Task AWhollyThrottledPool_ThrowsUpstreamRateLimited_WithTheShortestPark() + { + await using var a = new StubNode(() => 429); + await using var b = new StubNode(() => 429); + long now = 0; + var client = new HiveRpcClient(new[] { a.Url, b.Url }, timeoutMs: 500, failoverThreshold: 1, clock: () => now); + + var first = await Assert.ThrowsAsync(() => + client.Call("condenser_api", "get_accounts", new JsonArray())); + Assert.True(first.RetryAfterMs > 0); + + // Skipped as parked counts as throttled too, not as "no nodes". + now += 4_000; + var second = await Assert.ThrowsAsync(() => + client.Call("condenser_api", "get_accounts", new JsonArray())); + Assert.InRange(second.RetryAfterMs, 1, first.RetryAfterMs); + } + + [Fact] + public async Task ThrottledAndDown_IsNotReportedAsThrottled() + { + // A node that is down is a different failure: callers must not be told + // to back off and come back when part of the reason is an outage. + await using var throttled = new StubNode(() => 429); + await using var down = new StubNode(() => 500); + var client = new HiveRpcClient(new[] { throttled.Url, down.Url }, timeoutMs: 500, failoverThreshold: 1); + + var ex = await Assert.ThrowsAnyAsync(() => client.Call("condenser_api", "get_accounts", new JsonArray())); + Assert.IsNotType(ex); + } + + [Fact] + public async Task AParkedNode_StillServes_OnceEveryUnparkedNodeHasFailed() + { + // The one-probe allowance is what keeps a throttled pool recoverable: + // a node whose limit has lifted early is found before its park ends. + var throttledStatus = 429; + await using var throttled = new StubNode(() => throttledStatus); + await using var down = new StubNode(() => 500); + long now = 0; + var client = new HiveRpcClient(new[] { throttled.Url, down.Url }, timeoutMs: 500, failoverThreshold: 1, clock: () => now); + + await Assert.ThrowsAnyAsync(() => client.Call("condenser_api", "get_accounts", new JsonArray())); + throttledStatus = 200; + now += 1_000; + var result = await client.Call("condenser_api", "get_accounts", new JsonArray()); + Assert.Equal("served-by", result![0]!["name"]!.GetValue()); + Assert.Equal(2, throttled.Hits); + } + [Fact] public async Task AllNodesDown_Throws() { diff --git a/dotnet/EcencyApi.Tests/SsrRpcTests.cs b/dotnet/EcencyApi.Tests/SsrRpcTests.cs index 17e096dd..08729bd3 100644 --- a/dotnet/EcencyApi.Tests/SsrRpcTests.cs +++ b/dotnet/EcencyApi.Tests/SsrRpcTests.cs @@ -266,6 +266,41 @@ public async Task Unreachable_node_is_reported_as_unavailable() Assert.Equal(SsrRpc.Outcome.Unavailable, r.Outcome); } + [Fact] + public async Task A_throttled_upstream_answers_503_RATELIMITED_with_Retry_After_and_is_counted() + { + // Distinct from UNAVAILABLE (502): the consumer must be able to tell + // "the nodes are throttling this host" from "this proxy is broken", or it + // trips its breaker and sends every read to the same throttling nodes. + await using var stub = new RpcStub { Status = 429 }; + Use(stub); + SsrRpc.SecretDigest = SsrRpc.Digest("right-secret"); + try + { + var r = await SsrRpc.Resolve(Post, P("a", "b")); + Assert.Equal(SsrRpc.Outcome.RateLimited, r.Outcome); + + var ctx = Request("POST", "/private-api/ssr/rpc", "right-secret", + "{\"api\":\"bridge\",\"method\":\"get_post\",\"params\":{\"author\":\"a\",\"permlink\":\"c\"}}"); + await SsrRpc.Rpc(ctx); + Assert.Equal(503, ctx.Response.StatusCode); + Assert.Equal("RATELIMITED", ctx.Response.Headers["X-Ssr-Cache"].ToString()); + Assert.True(int.TryParse(ctx.Response.Headers.RetryAfter.ToString(), out var secs) && secs >= 1, + $"Retry-After '{ctx.Response.Headers.RetryAfter}'"); + + var stats = Request("GET", "/private-api/ssr/stats", "right-secret"); + await SsrRpc.Stats(stats); + var body = JsonNode.Parse(ResponseText(stats))!; + var m = body["methods"]!["bridge.get_post"]!; + Assert.Equal(2, m["rate_limited"]!.GetValue()); + Assert.Equal(0, m["error"]!.GetValue()); + } + finally + { + SsrRpc.SecretDigest = null; + } + } + [Fact] public async Task Fills_in_progress_are_bounded_so_distinct_keys_queue_instead_of_piling_up() { diff --git a/dotnet/EcencyApi/Handlers/PrivateApi.Recovery.cs b/dotnet/EcencyApi/Handlers/PrivateApi.Recovery.cs index 149d386a..a3cd1fd5 100644 --- a/dotnet/EcencyApi/Handlers/PrivateApi.Recovery.cs +++ b/dotnet/EcencyApi/Handlers/PrivateApi.Recovery.cs @@ -98,6 +98,7 @@ internal static (string Key, string Line) RecoveryReadFailureLog(string method, HttpRequestException => "http_error", // The RPC client's own node failure type (unreachable, bad status, bad body). _ when type == "NodeUnavailableException" => "http_error", + HiveRpcClient.UpstreamRateLimitedException => "http_error", HiveRpcClient.RpcException => "rpc_error", FormatException or System.Text.Json.JsonException => "parse_error", _ => "other", diff --git a/dotnet/EcencyApi/Handlers/SsrRpc.cs b/dotnet/EcencyApi/Handlers/SsrRpc.cs index 495098e0..125f993c 100644 --- a/dotnet/EcencyApi/Handlers/SsrRpc.cs +++ b/dotnet/EcencyApi/Handlers/SsrRpc.cs @@ -28,6 +28,10 @@ namespace EcencyApi.Handlers; /// - A lookup that outlives the budget answers 504 while the upstream call /// completes in the background and fills the cache; an RPC-level error /// answers 502. Either way the consumer falls back to its own node pool. +/// - A lookup that failed only because every node is rate-limiting this host +/// answers 503 RATELIMITED with a Retry-After. The proxy itself is fine, so +/// a consumer must not count it toward a breaker that would send its other +/// reads straight to the same throttling nodes. /// - No per-request logging (invariant 6); counters on /stats instead. /// public static partial class SsrRpc @@ -152,7 +156,7 @@ public bool TryExpire(int budgetMs) internal sealed class Counter { - public long Hit, Miss, Coalesced, Error, Timeout; + public long Hit, Miss, Coalesced, Error, Timeout, RateLimited; // Fills that outran the lookup budget. Distinct from Timeout, which is // counted once per waiting reader: one slow fill on a hot key is one // slow fill and many timeouts. @@ -226,9 +230,9 @@ internal static string CacheKey(MethodPolicy policy, JsonNode? @params) => // ---- core ---------------------------------------------------------------- - internal enum Outcome { Hit, Miss, Coalesced, Timeout, RpcError, Unavailable } + internal enum Outcome { Hit, Miss, Coalesced, Timeout, RpcError, Unavailable, RateLimited } - internal readonly record struct Resolution(Outcome Outcome, byte[] Bytes, string? Error); + internal readonly record struct Resolution(Outcome Outcome, byte[] Bytes, string? Error, int RetryAfterMs = 0); /// /// Answer one allowlisted call from the cache, or from one shared upstream @@ -318,6 +322,11 @@ internal static async Task Resolve(MethodPolicy policy, JsonNode @pa Interlocked.Increment(ref counter.Timeout); return new Resolution(Outcome.Timeout, Array.Empty(), "budget exceeded"); } + catch (HiveRpcClient.UpstreamRateLimitedException e) + { + Interlocked.Increment(ref counter.RateLimited); + return new Resolution(Outcome.RateLimited, Array.Empty(), e.Message, e.RetryAfterMs); + } catch (HiveRpcClient.RpcException e) { Interlocked.Increment(ref counter.Error); @@ -479,6 +488,10 @@ public static async Task Rpc(HttpContext ctx) case Outcome.Timeout: await ctx.SendJson(504, new JsonObject { ["error"] = "Upstream Timeout" }); return; + case Outcome.RateLimited: + ctx.Response.Headers.RetryAfter = ((resolution.RetryAfterMs + 999) / 1000).ToString(System.Globalization.CultureInfo.InvariantCulture); + await ctx.SendJson(503, new JsonObject { ["error"] = "Upstream Rate Limited" }); + return; default: await ctx.SendJson(502, new JsonObject { ["error"] = resolution.Error ?? "Upstream Error" }); return; @@ -511,6 +524,7 @@ public static async Task Stats(HttpContext ctx) ["coalesced"] = Interlocked.Read(ref c.Coalesced), ["error"] = Interlocked.Read(ref c.Error), ["timeout"] = Interlocked.Read(ref c.Timeout), + ["rate_limited"] = Interlocked.Read(ref c.RateLimited), ["slow_fill"] = Interlocked.Read(ref c.SlowFill), ["upstream_ms"] = Math.Round(c.ReadUpstreamMs(), 1), }; diff --git a/dotnet/EcencyApi/Infrastructure/HiveRpcClient.cs b/dotnet/EcencyApi/Infrastructure/HiveRpcClient.cs index 5e39ef9e..080f8f13 100644 --- a/dotnet/EcencyApi/Infrastructure/HiveRpcClient.cs +++ b/dotnet/EcencyApi/Infrastructure/HiveRpcClient.cs @@ -14,6 +14,10 @@ namespace EcencyApi.Infrastructure; /// (dhive semantics — an application error, not an unhealthy node). /// - Overload statuses (429/502/503/504) advance to the next node immediately /// instead of burning a same-node retry. +/// - A node parked for a 429 is asked at most once per call, and only one such +/// node per call: while the whole pool throttles this host, a call costs one +/// upstream request instead of one per node. A call that failed only on 429s +/// throws . /// - An `unknown method` answer to a call that names a fallback method asks /// the same node the fallback, and marks the node and the method's family /// for a while (CallMethod). @@ -247,11 +251,32 @@ private IEnumerable UnsupportedFamilies(int nodeIndex) => JsonNode? unpreferred = null; var haveUnpreferred = false; var unpreferredCount = 0; + // Throttling is only reported as such when it is the whole story: any + // other failure on the way (a timeout, a 5xx, a bad body) makes it a + // plain failure, so a caller is never told to just wait out an outage. + var sawRateLimit = false; + var sawOtherFailure = false; + var parkedProbeUsed = false; foreach (var nodeIndex in _health.OrderedNodeIndices(callClass)) { var node = _nodes[nodeIndex]; + // Decided now, not from the ordering snapshot: a node parked by a + // concurrent call since this one started is parked for it too. + if (_health.RateLimitedForMs(nodeIndex) > 0) + { + // One probe keeps the pool recoverable (a limit can lift before + // our park ends); probing every parked node is the load the 429 + // asked us to stop sending. + if (parkedProbeUsed) + { + sawRateLimit = true; + continue; + } + parkedProbeUsed = true; + } + for (var attempt = 0; attempt < _failoverThreshold; attempt++) { // The ordering above is a snapshot; admission is decided now. @@ -322,11 +347,16 @@ private IEnumerable UnsupportedFamilies(int nodeIndex) => lastError = e; if (e.IsRateLimit) { + sawRateLimit = true; _health.RecordRateLimited(nodeIndex, e.RetryAfterMs); } - else if (_health.RecordFailure(nodeIndex, NowMs - started, callClass, e.IsTimeout)) + else { - break; // this failure parked the node: no same-node retry + sawOtherFailure = true; + if (_health.RecordFailure(nodeIndex, NowMs - started, callClass, e.IsTimeout)) + { + break; // this failure parked the node: no same-node retry + } } if (e.AdvanceImmediately) { @@ -336,6 +366,7 @@ private IEnumerable UnsupportedFamilies(int nodeIndex) => catch (Exception e) { lastError = e; + sawOtherFailure = true; if (_health.RecordFailure(nodeIndex, NowMs - started, callClass)) { break; @@ -353,11 +384,34 @@ private IEnumerable UnsupportedFamilies(int nodeIndex) => // account really has no metadata), so return it instead of failing. if (haveUnpreferred) return unpreferred; + if (sawRateLimit && !sawOtherFailure) + { + throw new UpstreamRateLimitedException( + $"every RPC node is rate-limiting {method}", (int)Math.Min(int.MaxValue, _health.ShortestRateLimitParkMs())); + } + // Every node exhausted — surface the last transport error (dhive throws // after cycling the whole list). throw lastError ?? new InvalidOperationException("no RPC nodes configured"); } + /// + /// Every node this call could use was rate-limiting this host: each attempt + /// answered 429, or the node was skipped while parked for an earlier 429. + /// Distinct from a pool that is down, so a caller can back off for + /// instead of sending the read elsewhere. + /// + public sealed class UpstreamRateLimitedException : Exception + { + /// Until the soonest of the parks lapses, at least 1. + public int RetryAfterMs { get; } + + public UpstreamRateLimitedException(string message, int retryAfterMs) : base(message) + { + RetryAfterMs = Math.Max(1, retryAfterMs); + } + } + /// A node is unhealthy/unreachable; try the next one. Distinct from /// RpcException (a real RPC-level error that must not fail over). private sealed class NodeUnavailableException : Exception diff --git a/dotnet/EcencyApi/Infrastructure/NodeHealthTracker.cs b/dotnet/EcencyApi/Infrastructure/NodeHealthTracker.cs index 2d963efd..2ee7d6e6 100644 --- a/dotnet/EcencyApi/Infrastructure/NodeHealthTracker.cs +++ b/dotnet/EcencyApi/Infrastructure/NodeHealthTracker.cs @@ -268,7 +268,8 @@ private void RecordLatency(NodeHealth h, CallClass callClass, double elapsedMs) /// /// Node indices ordered best-first: unparked nodes sorted by /// (recent-failure tier, latency score, config index); rate-limit-parked - /// nodes appended last as a final resort. A node parked for consecutive + /// nodes appended last as a final resort, the park that lapses soonest + /// first (a caller that probes only one of them probes the likeliest). A node parked for consecutive /// failures is left out altogether while any other node is available (it /// was not answering; a throttled node might), and probed once its park /// lapses. When every node is failure-parked all are offered, so a pool @@ -296,7 +297,8 @@ public List OrderedNodeIndices(CallClass callClass) && p.SampleCount >= LatencyMinSamples && now - p.UpdatedAtMs <= LatencyMaxAgeMs; var score = latencyUsable ? p.EwmaMs!.Value : LatencyUnprovenPriorMs; - return (Index: i, Parked: parked, Dead: dead, RecentFailure: recentFailure, Score: score); + return (Index: i, Parked: parked, ParkedUntil: parked ? h.RateLimitedUntilMs : 0, + Dead: dead, RecentFailure: recentFailure, Score: score); }) .ToList(); if (ranked.Any(x => !x.Dead)) @@ -305,6 +307,7 @@ public List OrderedNodeIndices(CallClass callClass) } return ranked .OrderBy(x => x.Parked) + .ThenBy(x => x.ParkedUntil) .ThenBy(x => x.RecentFailure) .ThenBy(x => x.Score) .ThenBy(x => x.Index) @@ -313,6 +316,31 @@ public List OrderedNodeIndices(CallClass callClass) } } + /// How long the node stays parked for a 429, 0 when it is not. + public long RateLimitedForMs(int nodeIndex) + { + lock (_lock) + { + return Math.Max(0, _health[nodeIndex].RateLimitedUntilMs - NowMs); + } + } + + /// The shortest 429 park still running anywhere in the pool, 0 when none is. + public long ShortestRateLimitParkMs() + { + lock (_lock) + { + var now = NowMs; + long shortest = 0; + foreach (var h in _health) + { + var left = h.RateLimitedUntilMs - now; + if (left > 0 && (shortest == 0 || left < shortest)) shortest = left; + } + return shortest; + } + } + /// /// Admission at attempt time, because the ordering a call holds was taken /// when the call started and can be stale by the time it reaches this node: From 0c45200503b282c6273025c269acf3b8003bd2fc Mon Sep 17 00:00:00 2001 From: feruzm Date: Thu, 19 Nov 2026 13:16:16 +0000 Subject: [PATCH 2/4] Count a failure-parked or refused node as an outage, spend the parked probe only on a sent request A node left out of the ordering, or refused admission, never failed inside the call, so a pool of one dead and one throttled node was reported as throttled. The parked-node probe was marked used before admission, so a refused probe skipped the rest of the parked tier without a request. Retry-After is computed in long. --- .../EcencyApi.Tests/HiveRpcFailoverTests.cs | 20 ++++++++ dotnet/EcencyApi/Handlers/SsrRpc.cs | 3 +- .../EcencyApi/Infrastructure/HiveRpcClient.cs | 46 +++++++++++-------- 3 files changed, 50 insertions(+), 19 deletions(-) diff --git a/dotnet/EcencyApi.Tests/HiveRpcFailoverTests.cs b/dotnet/EcencyApi.Tests/HiveRpcFailoverTests.cs index 2db8c6ac..bc5d1591 100644 --- a/dotnet/EcencyApi.Tests/HiveRpcFailoverTests.cs +++ b/dotnet/EcencyApi.Tests/HiveRpcFailoverTests.cs @@ -760,6 +760,26 @@ public async Task ThrottledAndDown_IsNotReportedAsThrottled() Assert.IsNotType(ex); } + [Fact] + public async Task AParkedDeadNodeAndAThrottledNode_IsNotReportedAsThrottled() + { + // A node already parked for failing is left out of the ordering, so it + // never fails inside the call; it is still an outage, not throttling. + await using var dead = new StubNode(() => -1); + await using var throttled = new StubNode(() => 429); + long now = 0; + var client = new HiveRpcClient(new[] { dead.Url, throttled.Url }, timeoutMs: 200, failoverThreshold: 1, clock: () => now); + for (var i = 0; i < 3; i++) + { + if (i > 0) now += 61_000; // past the throttled node's park, inside nothing + await Assert.ThrowsAnyAsync(() => client.Call("condenser_api", "get_accounts", new JsonArray())); + } + Assert.True(client.HealthSnapshot()[0]!["parked_for_ms"]!.GetValue() > 0); + + var ex = await Assert.ThrowsAnyAsync(() => client.Call("condenser_api", "get_accounts", new JsonArray())); + Assert.IsNotType(ex); + } + [Fact] public async Task AParkedNode_StillServes_OnceEveryUnparkedNodeHasFailed() { diff --git a/dotnet/EcencyApi/Handlers/SsrRpc.cs b/dotnet/EcencyApi/Handlers/SsrRpc.cs index 125f993c..f2918a48 100644 --- a/dotnet/EcencyApi/Handlers/SsrRpc.cs +++ b/dotnet/EcencyApi/Handlers/SsrRpc.cs @@ -489,7 +489,8 @@ public static async Task Rpc(HttpContext ctx) await ctx.SendJson(504, new JsonObject { ["error"] = "Upstream Timeout" }); return; case Outcome.RateLimited: - ctx.Response.Headers.RetryAfter = ((resolution.RetryAfterMs + 999) / 1000).ToString(System.Globalization.CultureInfo.InvariantCulture); + // long: a node may send a Retry-After near int.MaxValue ms. + ctx.Response.Headers.RetryAfter = ((resolution.RetryAfterMs + 999L) / 1000).ToString(System.Globalization.CultureInfo.InvariantCulture); await ctx.SendJson(503, new JsonObject { ["error"] = "Upstream Rate Limited" }); return; default: diff --git a/dotnet/EcencyApi/Infrastructure/HiveRpcClient.cs b/dotnet/EcencyApi/Infrastructure/HiveRpcClient.cs index 080f8f13..d2fdf7f4 100644 --- a/dotnet/EcencyApi/Infrastructure/HiveRpcClient.cs +++ b/dotnet/EcencyApi/Infrastructure/HiveRpcClient.cs @@ -14,10 +14,10 @@ namespace EcencyApi.Infrastructure; /// (dhive semantics — an application error, not an unhealthy node). /// - Overload statuses (429/502/503/504) advance to the next node immediately /// instead of burning a same-node retry. -/// - A node parked for a 429 is asked at most once per call, and only one such -/// node per call: while the whole pool throttles this host, a call costs one -/// upstream request instead of one per node. A call that failed only on 429s -/// throws . +/// - Only one node parked for a 429 is asked per call (the one whose park +/// lapses soonest), after every unparked node: while the whole pool throttles +/// this host, a call reaches one node instead of all of them. A call that +/// failed only on 429s throws . /// - An `unknown method` answer to a call that names a fallback method asks /// the same node the fallback, and marks the node and the method's family /// for a while (CallMethod). @@ -258,29 +258,39 @@ private IEnumerable UnsupportedFamilies(int nodeIndex) => var sawOtherFailure = false; var parkedProbeUsed = false; - foreach (var nodeIndex in _health.OrderedNodeIndices(callClass)) + var ordered = _health.OrderedNodeIndices(callClass); + // A node left out of the ordering is parked for failing: part of the + // pool is down, so this call cannot be "only throttled". + if (ordered.Count < _nodes.Length) sawOtherFailure = true; + + foreach (var nodeIndex in ordered) { var node = _nodes[nodeIndex]; // Decided now, not from the ordering snapshot: a node parked by a - // concurrent call since this one started is parked for it too. - if (_health.RateLimitedForMs(nodeIndex) > 0) + // concurrent call since this one started is parked for it too. One + // probe keeps the pool recoverable (a limit can lift before our park + // ends); probing every parked node is the load the 429 asked us to + // stop sending. + var parkedNow = _health.RateLimitedForMs(nodeIndex) > 0; + if (parkedNow && parkedProbeUsed) { - // One probe keeps the pool recoverable (a limit can lift before - // our park ends); probing every parked node is the load the 429 - // asked us to stop sending. - if (parkedProbeUsed) - { - sawRateLimit = true; - continue; - } - parkedProbeUsed = true; + sawRateLimit = true; + continue; } for (var attempt = 0; attempt < _failoverThreshold; attempt++) { - // The ordering above is a snapshot; admission is decided now. - if (!_health.TryBeginAttempt(nodeIndex)) break; + // The ordering above is a snapshot; admission is decided now. A + // refusal means the node is failure-parked or a probe of it is in + // flight: an outage, not throttling, and no request was sent, so + // it does not spend the parked-node probe either. + if (!_health.TryBeginAttempt(nodeIndex)) + { + sawOtherFailure = true; + break; + } + if (parkedNow) parkedProbeUsed = true; var started = NowMs; try { From fc6e22d5a2f23e2c850f30d8aede304f551cdc4f Mon Sep 17 00:00:00 2001 From: feruzm Date: Thu, 19 Nov 2026 13:29:56 +0000 Subject: [PATCH 3/4] Choose the parked-node probe after the pass, admit under one lock A node parked by a concurrent call mid-call could take the single probe from an older park (the furthest from lapsing), or be requested without spending it when the park landed between the check and admission. Parked nodes are now deferred during the pass and one probe goes to the soonest-lapsing of them. Admission checks the failure park first, then the 429 park, under one lock, so a node that is both counts as an outage. Retry-After comes from the nodes this call saw throttled, a lapsed park counting as 0. --- .../EcencyApi.Tests/HiveRpcFailoverTests.cs | 56 +++++++++++++++++ .../EcencyApi/Infrastructure/HiveRpcClient.cs | 61 ++++++++++++------- .../Infrastructure/NodeHealthTracker.cs | 34 +++++------ 3 files changed, 111 insertions(+), 40 deletions(-) diff --git a/dotnet/EcencyApi.Tests/HiveRpcFailoverTests.cs b/dotnet/EcencyApi.Tests/HiveRpcFailoverTests.cs index bc5d1591..a6e424a4 100644 --- a/dotnet/EcencyApi.Tests/HiveRpcFailoverTests.cs +++ b/dotnet/EcencyApi.Tests/HiveRpcFailoverTests.cs @@ -799,6 +799,62 @@ public async Task AParkedNode_StillServes_OnceEveryUnparkedNodeHasFailed() Assert.Equal(2, throttled.Hits); } + [Fact] + public async Task ANodeThrottledMidCall_DoesNotTakeTheProbeFromTheSoonestPark() + { + // The ordering is a snapshot. A node another call parks while this one + // runs is the furthest from lapsing, so it must not take the single + // probe; the soonest-lapsing parked node gets it. + HiveRpcClient client = null!; + long now = 0; + await using var a = new StubNode(() => { client.Health.RecordRateLimited(1, null); return 500; }); + await using var b = new StubNode(() => 429); + await using var c = new StubNode(() => 200); + client = new HiveRpcClient(new[] { a.Url, b.Url, c.Url }, timeoutMs: 500, failoverThreshold: 1, clock: () => now); + client.Health.RecordRateLimited(2, null); // c parked first: lapses first + now = 5_000; + + var result = await client.Call("condenser_api", "get_accounts", new JsonArray()); + Assert.Equal("served-by", result![0]!["name"]!.GetValue()); + Assert.Equal(0, b.Hits); + Assert.Equal(1, c.Hits); + } + + [Fact] + public async Task ANodeDownAndThrottled_IsAnOutage_EvenAfterTheProbeIsSpent() + { + HiveRpcClient client = null!; + long now = 0; + await using var x = new StubNode(() => + { + client.Health.RecordRateLimited(1, null); + client.Health.RecordRateLimited(2, null); + for (var i = 0; i < 3; i++) client.Health.RecordFailure(2, 10, CallClass.Cheap, timedOut: true); + return 429; + }); + await using var y = new StubNode(() => 429); + await using var z = new StubNode(() => 429); + client = new HiveRpcClient(new[] { x.Url, y.Url, z.Url }, timeoutMs: 500, failoverThreshold: 1, clock: () => now); + + var ex = await Assert.ThrowsAnyAsync(() => client.Call("condenser_api", "get_accounts", new JsonArray())); + Assert.IsNotType(ex); + } + + [Fact] + public async Task RetryAfter_CountsAParkThatLapsedDuringTheCall() + { + // The first node's park lapses while the second is answering: it can + // serve now, so the advised wait is the minimum, not the second's park. + long now = 0; + await using var a = new StubNode(() => 429); + await using var b = new StubNode(() => { now += 11_000; return 429; }); + var client = new HiveRpcClient(new[] { a.Url, b.Url }, timeoutMs: 500, failoverThreshold: 1, clock: () => now); + + var ex = await Assert.ThrowsAsync(() => + client.Call("condenser_api", "get_accounts", new JsonArray())); + Assert.Equal(1, ex.RetryAfterMs); + } + [Fact] public async Task AllNodesDown_Throws() { diff --git a/dotnet/EcencyApi/Infrastructure/HiveRpcClient.cs b/dotnet/EcencyApi/Infrastructure/HiveRpcClient.cs index d2fdf7f4..977abc0e 100644 --- a/dotnet/EcencyApi/Infrastructure/HiveRpcClient.cs +++ b/dotnet/EcencyApi/Infrastructure/HiveRpcClient.cs @@ -15,7 +15,7 @@ namespace EcencyApi.Infrastructure; /// - Overload statuses (429/502/503/504) advance to the next node immediately /// instead of burning a same-node retry. /// - Only one node parked for a 429 is asked per call (the one whose park -/// lapses soonest), after every unparked node: while the whole pool throttles +/// lapses soonest, chosen after every unparked node was tried): while the whole pool throttles /// this host, a call reaches one node instead of all of them. A call that /// failed only on 429s throws . /// - An `unknown method` answer to a call that names a fallback method asks @@ -38,6 +38,9 @@ public sealed class HiveRpcClient private readonly Func _clock; private int _seq; + /// Test seam: the pool's health state, to stage parks mid-call. + internal NodeHealthTracker Health => _health; + // Per node, the fallback families it answered `unknown method` for and until // when (on _clock). Bounded by nodes x families; see CallMethod. private readonly ConcurrentDictionary<(int Node, string Family), long> _lacksUntil = new(); @@ -256,41 +259,54 @@ private IEnumerable UnsupportedFamilies(int nodeIndex) => // plain failure, so a caller is never told to just wait out an outage. var sawRateLimit = false; var sawOtherFailure = false; - var parkedProbeUsed = false; + // Nodes this call found parked for a 429 (deferred) or saw answer 429: + // the advised wait is how long until the first of them can serve again. + var deferred = new List(); + var throttledNodes = new HashSet(); var ordered = _health.OrderedNodeIndices(callClass); // A node left out of the ordering is parked for failing: part of the // pool is down, so this call cannot be "only throttled". if (ordered.Count < _nodes.Length) sawOtherFailure = true; - foreach (var nodeIndex in ordered) + // Every node in order, skipping the ones parked for a 429 at the moment + // they come up (the ordering is a snapshot; another call may have parked + // one since). Then ONE probe, to the deferred node whose park lapses + // soonest by then: it keeps the pool recoverable when a limit lifts + // early, while probing every parked node is the load the 429s asked us + // to stop sending. Chosen after the pass, so a node parked mid-call (the + // furthest from lapsing) cannot take the probe from an older park. + IEnumerable<(int Node, bool Probe)> Sequence() { - var node = _nodes[nodeIndex]; - - // Decided now, not from the ordering snapshot: a node parked by a - // concurrent call since this one started is parked for it too. One - // probe keeps the pool recoverable (a limit can lift before our park - // ends); probing every parked node is the load the 429 asked us to - // stop sending. - var parkedNow = _health.RateLimitedForMs(nodeIndex) > 0; - if (parkedNow && parkedProbeUsed) + foreach (var i in ordered) yield return (i, false); + if (deferred.Count > 0) { - sawRateLimit = true; - continue; + yield return (deferred.OrderBy(i => _health.RateLimitedForMs(i)).First(), true); } + } + + foreach (var (nodeIndex, isProbe) in Sequence()) + { + var node = _nodes[nodeIndex]; for (var attempt = 0; attempt < _failoverThreshold; attempt++) { - // The ordering above is a snapshot; admission is decided now. A - // refusal means the node is failure-parked or a probe of it is in - // flight: an outage, not throttling, and no request was sent, so - // it does not spend the parked-node probe either. - if (!_health.TryBeginAttempt(nodeIndex)) + // Admission is decided now, under one lock with the park check. + var admission = _health.Admit(nodeIndex, allowRateLimitParked: isProbe); + if (admission == NodeHealthTracker.Admission.RateLimitParked) + { + sawRateLimit = true; + throttledNodes.Add(nodeIndex); + if (attempt == 0) deferred.Add(nodeIndex); + break; + } + if (admission == NodeHealthTracker.Admission.Refused) { + // Failure-parked, or a probe of it is already in flight: an + // outage, not throttling. No request was sent. sawOtherFailure = true; break; } - if (parkedNow) parkedProbeUsed = true; var started = NowMs; try { @@ -358,6 +374,7 @@ private IEnumerable UnsupportedFamilies(int nodeIndex) => if (e.IsRateLimit) { sawRateLimit = true; + throttledNodes.Add(nodeIndex); _health.RecordRateLimited(nodeIndex, e.RetryAfterMs); } else @@ -396,8 +413,10 @@ private IEnumerable UnsupportedFamilies(int nodeIndex) => if (sawRateLimit && !sawOtherFailure) { + // A park that lapsed during the call counts as 0: that node can serve now. + var wait = throttledNodes.Min(i => _health.RateLimitedForMs(i)); throw new UpstreamRateLimitedException( - $"every RPC node is rate-limiting {method}", (int)Math.Min(int.MaxValue, _health.ShortestRateLimitParkMs())); + $"every RPC node is rate-limiting {method}", (int)Math.Min(int.MaxValue, wait)); } // Every node exhausted — surface the last transport error (dhive throws diff --git a/dotnet/EcencyApi/Infrastructure/NodeHealthTracker.cs b/dotnet/EcencyApi/Infrastructure/NodeHealthTracker.cs index 2ee7d6e6..95aab542 100644 --- a/dotnet/EcencyApi/Infrastructure/NodeHealthTracker.cs +++ b/dotnet/EcencyApi/Infrastructure/NodeHealthTracker.cs @@ -325,22 +325,6 @@ public long RateLimitedForMs(int nodeIndex) } } - /// The shortest 429 park still running anywhere in the pool, 0 when none is. - public long ShortestRateLimitParkMs() - { - lock (_lock) - { - var now = NowMs; - long shortest = 0; - foreach (var h in _health) - { - var left = h.RateLimitedUntilMs - now; - if (left > 0 && (shortest == 0 || left < shortest)) shortest = left; - } - return shortest; - } - } - /// /// Admission at attempt time, because the ordering a call holds was taken /// when the call started and can be stale by the time it reaches this node: @@ -350,7 +334,18 @@ public long ShortestRateLimitParkMs() /// rule yields when no other node could take the attempt. Pair with /// . /// - public bool TryBeginAttempt(int nodeIndex) + public bool TryBeginAttempt(int nodeIndex) => Admit(nodeIndex, allowRateLimitParked: true) == Admission.Admitted; + + public enum Admission { Admitted, RateLimitParked, Refused } + + /// + /// plus, when + /// is false, a node parked for a 429 is not admitted (RateLimitParked), decided + /// under the same lock so a concurrent park cannot slip in between. A node that + /// is failure-parked is Refused first, even if it is also rate-limit parked: an + /// outage outranks throttling. Admitted pairs with . + /// + public Admission Admit(int nodeIndex, bool allowRateLimitParked) { lock (_lock) { @@ -369,10 +364,11 @@ public bool TryBeginAttempt(int nodeIndex) var oBusy = !oParked && o.FailureParkStreak > 0 && o.InFlight > 0; othersAvailable = !oParked && !oBusy; } - if (othersAvailable) return false; + if (othersAvailable) return Admission.Refused; } + if (!allowRateLimitParked && h.RateLimitedUntilMs > now) return Admission.RateLimitParked; h.InFlight++; - return true; + return Admission.Admitted; } } From fb87939a47db0c74dccb2d1389a1c7e43005eacb Mon Sep 17 00:00:00 2001 From: feruzm Date: Thu, 19 Nov 2026 13:36:33 +0000 Subject: [PATCH 4/4] Pass a refused parked-node probe on to the next candidate A deferred node can go down, or be probed by another call, between the pass and the probe. Admission then refuses it with no request sent, so try the next soonest-lapsing candidate until one request goes out. --- .../EcencyApi.Tests/HiveRpcFailoverTests.cs | 25 +++++++++++++++++++ .../EcencyApi/Infrastructure/HiveRpcClient.cs | 13 +++++++--- 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/dotnet/EcencyApi.Tests/HiveRpcFailoverTests.cs b/dotnet/EcencyApi.Tests/HiveRpcFailoverTests.cs index a6e424a4..8dd94a16 100644 --- a/dotnet/EcencyApi.Tests/HiveRpcFailoverTests.cs +++ b/dotnet/EcencyApi.Tests/HiveRpcFailoverTests.cs @@ -820,6 +820,31 @@ public async Task ANodeThrottledMidCall_DoesNotTakeTheProbeFromTheSoonestPark() Assert.Equal(1, c.Hits); } + [Fact] + public async Task ARefusedProbe_PassesToTheNextParkedNode() + { + // c is parked (soonest) after this call's snapshot and deferred; then, + // still inside the pass, it goes down. At probe time it is refused with + // no request sent, so the probe passes to the next parked node, b. + HiveRpcClient client = null!; + long now = 0; + await using var a = new StubNode(() => { client.Health.RecordRateLimited(1, 1); return 500; }); + await using var c = new StubNode(() => 200); + await using var d = new StubNode(() => + { + for (var i = 0; i < 3; i++) client.Health.RecordFailure(1, 10, CallClass.Cheap, timedOut: true); + return 500; + }); + await using var b = new StubNode(() => 200); + client = new HiveRpcClient(new[] { a.Url, c.Url, d.Url, b.Url }, timeoutMs: 500, failoverThreshold: 1, clock: () => now); + client.Health.RecordRateLimited(3, null); // b parked before the call: last in the snapshot + + var result = await client.Call("condenser_api", "get_accounts", new JsonArray()); + Assert.Equal("served-by", result![0]!["name"]!.GetValue()); + Assert.Equal(0, c.Hits); + Assert.Equal(1, b.Hits); + } + [Fact] public async Task ANodeDownAndThrottled_IsAnOutage_EvenAfterTheProbeIsSpent() { diff --git a/dotnet/EcencyApi/Infrastructure/HiveRpcClient.cs b/dotnet/EcencyApi/Infrastructure/HiveRpcClient.cs index 977abc0e..bc01df91 100644 --- a/dotnet/EcencyApi/Infrastructure/HiveRpcClient.cs +++ b/dotnet/EcencyApi/Infrastructure/HiveRpcClient.cs @@ -275,13 +275,19 @@ private IEnumerable UnsupportedFamilies(int nodeIndex) => // soonest by then: it keeps the pool recoverable when a limit lifts // early, while probing every parked node is the load the 429s asked us // to stop sending. Chosen after the pass, so a node parked mid-call (the - // furthest from lapsing) cannot take the probe from an older park. + // furthest from lapsing) cannot take the probe from an older park. A + // candidate refused at probe time (down, or probed by another call + // meanwhile) got no request, so the probe passes to the next one. + var probeSent = false; IEnumerable<(int Node, bool Probe)> Sequence() { foreach (var i in ordered) yield return (i, false); - if (deferred.Count > 0) + var candidates = new List(deferred); + while (!probeSent && candidates.Count > 0) { - yield return (deferred.OrderBy(i => _health.RateLimitedForMs(i)).First(), true); + var next = candidates.OrderBy(i => _health.RateLimitedForMs(i)).First(); + candidates.Remove(next); + yield return (next, true); } } @@ -307,6 +313,7 @@ private IEnumerable UnsupportedFamilies(int nodeIndex) => sawOtherFailure = true; break; } + if (isProbe) probeSent = true; var started = NowMs; try {