diff --git a/CLAUDE.md b/CLAUDE.md index 68829bbf..ab5ef07a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -68,7 +68,7 @@ Handlers are `public static async Task Name(HttpContext ctx)` methods on static ## Upstream node failover -`NodeHealthTracker` (adopted from the vision-web SDK) holds per-node health state: 429 responses park a node for `Retry-After` (or an escalating window), recent failures deprioritize it, and a latency EWMA orders the pool best-first with config order as tiebreak. That EWMA is kept per **call class** (`CallClass.Cheap` / `CallClass.Heavy`) because upstream cost is bimodal: a point read costs a fraction of a feed-shaped query, while which node is quickest differs between the two. A caller says which class a call belongs to and the pool is ordered from that class's profile. Each node also has a **window cap**: several public nodes accept a fixed number of calls per rolling minute per client and 429 the rest, so the tracker counts calls sent per node over the last 60s, learns the cap from the count when a 429 comes back (only from 100 calls up; fewer means a burst limiter or a passing episode), skips a node at its cap without a request (`Admission.AtCap`, still a last-resort candidate), lowers the cap on a 429 below it (below 100, an ordinary send's 429 halves it, once per burst (only sends made after the last cut count), never under the count it came at), refunds exactly the refused send (`SendTicket`; the unknown-method fallback is counted as its own send and is not sent past the cap, except on the last-resort probe), and raises it by half after a whole window spent at it with no 429. A 429 with `Retry-After` parks for exactly that long and does not climb the escalation ladder. Everything about *whether* a node is answering (consecutive failures, failure parking, rate-limit parking, half-open admission) stays node-wide. Two clients build on it: +`NodeHealthTracker` (adopted from the vision-web SDK) holds per-node health state: 429 responses park a node for `Retry-After` (or an escalating window), recent failures deprioritize it, and a latency EWMA orders the pool best-first with config order as tiebreak. That EWMA is kept per **call class** (`CallClass.Cheap` / `CallClass.Heavy`) because upstream cost is bimodal: a point read costs a fraction of a feed-shaped query, while which node is quickest differs between the two. A caller says which class a call belongs to and the pool is ordered from that class's profile. Everything about *whether* a node is answering (consecutive failures, failure parking, rate-limit parking, half-open admission) stays node-wide. Two clients build on it: - `HiveRpcClient` (Hive JSON-RPC): RPC-level errors (JSON `error` field) surface immediately without failover — they're application errors, not node health. The typed helpers additionally validate the result *shape* (`get_accounts` → array, `get_dynamic_global_properties` → object): a 200 with valid JSON but no usable result is a node failure that fails over — without this, a node serving malformed 200s is recorded as healthy and stays ranked first (observed in production as multi-hour windows of token-validation 401s). - `EngineRpcClient` (Hive-Engine): one instance per pool — the `/contracts` RPC pool and the history-API pool. The portfolio `Find` calls are fixed-shape queries that always yield a `result` array on a healthy node, so an error payload or non-JSON body *is* a node failure and rolls over to the next node. The raw passthroughs (`engine-api`, `engine-account-history`) fail over only on transport errors and 429/5xx; other responses belong to the caller's query and pipe as-is. diff --git a/dotnet/EcencyApi.Tests/HiveRpcFailoverTests.cs b/dotnet/EcencyApi.Tests/HiveRpcFailoverTests.cs index b6e508fd..1be2415a 100644 --- a/dotnet/EcencyApi.Tests/HiveRpcFailoverTests.cs +++ b/dotnet/EcencyApi.Tests/HiveRpcFailoverTests.cs @@ -1031,133 +1031,4 @@ public async Task AllNodesDown_Throws() await Assert.ThrowsAnyAsync(() => client.Call("condenser_api", "get_accounts", new JsonArray())); } - - [Fact] - public async Task AWindowLimitedNode_IsSentWhatItAccepts_InsteadOfBeingOverrunEachTimeItsParkLapses() - { - // A node that accepts 150 calls per rolling minute (on the test clock) and - // answers the rest 429 with Retry-After: 1, like the nodes that cap per - // 60s. A healthy, slightly slower second node takes the overflow. - const int limit = 150; - long now = 0; - var accepted = new List(); - var refused = 0; - await using var limited = new StubNode(() => - { - lock (accepted) - { - accepted.RemoveAll(t => t <= now - 60_000); - if (accepted.Count < limit) { accepted.Add(now); return 200; } - refused++; - return 429; - } - }); - limited.Headers["Retry-After"] = "1"; - await using var spare = new StubNode(() => { Thread.Sleep(5); return 200; }); - var client = new HiveRpcClient(new[] { limited.Url, spare.Url }, timeoutMs: 1000, failoverThreshold: 1, - clock: () => now); - - // 20 concurrent calls a second for 90s: concurrency is what overruns a - // node, since every call that starts together picks the same best node. - var served = 0; - for (var tick = 0; tick < 90; tick++) - { - var batch = await Task.WhenAll(Enumerable.Range(0, 20).Select(_ => - client.Call("condenser_api", "get_accounts", new JsonArray()))); - served += batch.Count(r => (string?)r?[0]?["port"] == limited.Url); - now += 1_000; - } - - // Without the cap: a batch of 429s each time the node comes back into - // play while its window is still full. With it: the first crossing only. - Assert.InRange(refused, 1, 15); - // ...and it still serves what it accepts (two windows' worth in 90s). - Assert.True(served >= 2 * limit - 20, $"served {served}"); - } - - [Fact] - public async Task AnUnknownMethodFallback_CountsAsItsOwnSend() - { - await using var node = new StubNode(m => m == "bridge.get_post_v2" ? -6 : 200); - var client = new HiveRpcClient(new[] { node.Url }, timeoutMs: 1000, failoverThreshold: 1, clock: () => 0); - await client.CallMethod("bridge.get_post_v2", new JsonObject(), - fallback: ("bridge.get_post", new JsonObject(), "post_v2")); - Assert.Equal(2, node.Hits); - Assert.Equal(2, client.Health.Snapshot()[0].WindowSent); - } - - [Fact] - public async Task AFallbackAnswered429_RefundsOnlyItself() - { - await using var node = new StubNode(m => m == "bridge.get_post_v2" ? -6 : 429); - var client = new HiveRpcClient(new[] { node.Url }, timeoutMs: 1000, failoverThreshold: 1, clock: () => 0); - await Assert.ThrowsAnyAsync(() => client.CallMethod("bridge.get_post_v2", new JsonObject(), - fallback: ("bridge.get_post", new JsonObject(), "post_v2"))); - Assert.Equal(2, node.Hits); - // The node took the first request; only the refused fallback comes off. - Assert.Equal(1, client.Health.Snapshot()[0].WindowSent); - } - - [Fact] - public async Task AFallbackThatWouldPassTheCap_IsNotSent_AndTheCallMovesOn() - { - await using var lacking = new StubNode(m => m == "bridge.get_post_v2" ? -6 : 200); - await using var spare = new StubNode(() => 200); - long now = 0; - var client = new HiveRpcClient(new[] { lacking.Url, spare.Url }, timeoutMs: 1000, failoverThreshold: 1, - clock: () => now); - // The lacking node has room for exactly one more request this window. - var health = client.Health; - for (var i = 0; i < 150; i++) - { - health.Admit(0, allowRateLimitParked: false, out _); - health.EndAttempt(0); - } - health.Admit(0, allowRateLimitParked: false, out var refused); - health.RecordRateLimited(0, 0, refused); - health.EndAttempt(0); - Assert.Equal(150, health.Snapshot()[0].WindowCap); - health.Admit(0, allowRateLimitParked: true, out var probe); // leave it one short - health.RecordRateLimited(0, 0, probe); - health.EndAttempt(0); - now += 60_001; - for (var i = 0; i < 149; i++) - { - health.Admit(0, allowRateLimitParked: false, out _); - health.EndAttempt(0); - } - - var result = await client.CallMethod("bridge.get_post_v2", new JsonObject(), - fallback: ("bridge.get_post", new JsonObject(), "post_v2")); - Assert.Equal(spare.Url, (string?)result?[0]?["port"]); - // The primary used the last slot; the fallback was not sent over the cap. - Assert.Equal(1, lacking.Hits); - Assert.Equal(150, health.Snapshot()[0].WindowSent); - } - - [Fact] - public async Task AFallbackOnALastResortProbe_IsSentPastTheCap() - { - await using var lacking = new StubNode(m => m == "bridge.get_post_v2" ? -6 : 200); - long now = 0; - var client = new HiveRpcClient(new[] { lacking.Url }, timeoutMs: 1000, failoverThreshold: 1, - clock: () => now); - var health = client.Health; - for (var i = 0; i < 150; i++) - { - health.Admit(0, allowRateLimitParked: false, out _); - health.EndAttempt(0); - } - health.Admit(0, allowRateLimitParked: false, out var refused); - health.RecordRateLimited(0, 0, refused); - health.EndAttempt(0); - now += 1; - - // At its cap and the only node: the call goes out as the last resort, - // fallback included, rather than failing. - var result = await client.CallMethod("bridge.get_post_v2", new JsonObject(), - fallback: ("bridge.get_post", new JsonObject(), "post_v2")); - Assert.Equal(lacking.Url, (string?)result?[0]?["port"]); - Assert.Equal(2, lacking.Hits); - } } diff --git a/dotnet/EcencyApi.Tests/NodeWindowCapTests.cs b/dotnet/EcencyApi.Tests/NodeWindowCapTests.cs deleted file mode 100644 index 801d5958..00000000 --- a/dotnet/EcencyApi.Tests/NodeWindowCapTests.cs +++ /dev/null @@ -1,350 +0,0 @@ -using EcencyApi.Infrastructure; -using Xunit; - -namespace EcencyApi.Tests; - -/// -/// The per-node window cap (#128): a node that answers 429 once it has -/// accepted a fixed number of calls in a rolling minute is sent no more than -/// that number, instead of being overrun and parked over and over. -/// -public class NodeWindowCapTests -{ - private const int Window = 60_000; - - private static void Send(NodeHealthTracker t, int node, int count) - { - for (var i = 0; i < count; i++) - { - Assert.Equal(NodeHealthTracker.Admission.Admitted, t.Admit(node, allowRateLimitParked: false)); - t.RecordSuccess(node, 50, CallClass.Cheap); - t.EndAttempt(node); - } - } - - /// One more call, answered 429. A probe is a last-resort send past - /// a park or the cap; otherwise the call is admitted the ordinary way. - private static void Refused(NodeHealthTracker t, int node, int? retryAfterMs = 0, bool probe = false) - { - Assert.Equal(NodeHealthTracker.Admission.Admitted, t.Admit(node, allowRateLimitParked: probe, out var sent)); - t.RecordRateLimited(node, retryAfterMs, sent); - t.EndAttempt(node); - } - - private static NodeHealthTracker.NodeView View(NodeHealthTracker t, int node) => t.Snapshot()[node]; - - [Fact] - public void ANodeThatNeverRateLimited_HasNoCap() - { - long now = 0; - var t = new NodeHealthTracker(1, () => now); - Send(t, 0, 5_000); - Assert.Null(View(t, 0).WindowCap); - Assert.Equal(5_000, View(t, 0).WindowSent); - } - - [Fact] - public void A429AfterAFullWindow_SetsTheCap_AndTheNodeIsSkippedUntilTheWindowMoves() - { - long now = 0; - var t = new NodeHealthTracker(2, () => now); - Send(t, 0, 600); - now += 10; - Refused(t, 0); - Assert.Equal(600, View(t, 0).WindowCap); - // The refused call is refunded: the node did not count it either. - Assert.Equal(600, View(t, 0).WindowSent); - - now += 10; // the Retry-After park (0) is over; the window is still full - Assert.Equal(NodeHealthTracker.Admission.AtCap, t.Admit(0, allowRateLimitParked: false)); - Assert.True(t.ThrottledForMs(0) > 0); - - now = Window + 1; // the first 600 have left the window - Assert.Equal(NodeHealthTracker.Admission.Admitted, t.Admit(0, allowRateLimitParked: false)); - } - - [Fact] - public void A429AfterFewCalls_IsABurstOrAnEpisode_AndSetsNoCap() - { - long now = 0; - var t = new NodeHealthTracker(1, () => now); - Send(t, 0, 99); - Refused(t, 0); - Assert.Null(View(t, 0).WindowCap); - } - - [Fact] - public void A429BelowTheCap_LowersIt() - { - long now = 0; - var t = new NodeHealthTracker(1, () => now); - Send(t, 0, 600); - Refused(t, 0); - Assert.Equal(600, View(t, 0).WindowCap); - - now += Window + 1; // a fresh window; the operator has halved the limit - Send(t, 0, 300); - Refused(t, 0); - Assert.Equal(300, View(t, 0).WindowCap); - } - - [Fact] - public void A429WellBelowTheCap_HalvesItTowardsTheCountItCameAt() - { - long now = 0; - var t = new NodeHealthTracker(1, () => now); - Send(t, 0, 600); - Refused(t, 0); - Assert.Equal(600, View(t, 0).WindowCap); - - // The operator drops the limit to 50: each 429 inside the cap halves it, - // never below the count the 429 came at. - foreach (var expected in new[] { 300, 150, 75, 50 }) - { - now += Window + 1; - Send(t, 0, 50); - Refused(t, 0); - Assert.Equal(expected, View(t, 0).WindowCap); - } - // Settled: the next window's 51st call is no longer sent. - now += Window + 1; - Send(t, 0, 50); - Assert.Equal(NodeHealthTracker.Admission.AtCap, t.Admit(0, allowRateLimitParked: false)); - } - - [Fact] - public void ABurstOf429s_HalvesTheCapOnce() - { - long now = 0; - var t = new NodeHealthTracker(1, () => now); - Send(t, 0, 2_000); - Refused(t, 0); - now += Window + 1; - Send(t, 0, 50); - // Thirty calls already in flight when the node starts refusing: one - // verdict, not thirty, or one episode would ratchet the cap to the floor. - var inFlight = new List(); - for (var i = 0; i < 30; i++) - { - Assert.Equal(NodeHealthTracker.Admission.Admitted, t.Admit(0, allowRateLimitParked: false, out var sent)); - inFlight.Add(sent); - } - foreach (var sent in inFlight) - { - t.RecordRateLimited(0, 5_000, sent); - t.EndAttempt(0); - } - Assert.Equal(1_000, View(t, 0).WindowCap); - } - - [Theory] - [InlineData(0)] // Retry-After: 0 - [InlineData(null)] // none: our own ladder - public void ABurstOf429s_HalvesTheCapOnce_WhateverThePark(int? retryAfterMs) - { - long now = 0; - var t = new NodeHealthTracker(1, () => now); - Send(t, 0, 2_000); - Refused(t, 0); - now += Window + 1; - Send(t, 0, 50); - var inFlight = new List(); - for (var i = 0; i < 30; i++) - { - Assert.Equal(NodeHealthTracker.Admission.Admitted, t.Admit(0, allowRateLimitParked: false, out var sent)); - inFlight.Add(sent); - } - // The replies trickle in; with Retry-After: 0 no park is left between them. - foreach (var sent in inFlight) - { - now += 5; - t.RecordRateLimited(0, retryAfterMs, sent); - t.EndAttempt(0); - } - Assert.Equal(1_000, View(t, 0).WindowCap); - - // A call sent after the cut (and after any park) and refused again is a - // new verdict. - now += 60_001; - Refused(t, 0); - Assert.Equal(500, View(t, 0).WindowCap); - } - - [Fact] - public void A429ToAProbe_AtALowCount_LeavesTheCap() - { - long now = 0; - var t = new NodeHealthTracker(1, () => now); - Send(t, 0, 600); - Refused(t, 0, retryAfterMs: 30_000); - now += Window + 1; - // Still parked: a last-resort probe sent into the park is expected to be - // refused, and says nothing new about the window. - Send(t, 0, 0); - Refused(t, 0, retryAfterMs: 30_000, probe: true); - Assert.Equal(600, View(t, 0).WindowCap); - } - - [Fact] - public void A429RefundsItsOwnSend_NotTheNewestOne() - { - long now = 0; - var t = new NodeHealthTracker(1, () => now); - // An older call still in flight when newer ones are sent and answered. - Assert.Equal(NodeHealthTracker.Admission.Admitted, t.Admit(0, allowRateLimitParked: false, out var older)); - now = 30_000; - Send(t, 0, 150); - t.RecordRateLimited(0, 0, older); - t.EndAttempt(0); - Assert.Equal(150, View(t, 0).WindowCap); - // All 150 counted calls were sent at 30s, so the first slot frees at 90s, - // not when the refused call from 0s would have left. - Assert.Equal(Window, t.ThrottledForMs(0)); - } - - [Fact] - public void A429WithoutASend_RefundsNothing() - { - long now = 0; - var t = new NodeHealthTracker(1, () => now); - Send(t, 0, 150); - // A caller that never admitted (the Hive-Engine client) still parks. - t.RecordRateLimited(0, 1_000); - Assert.Equal(150, View(t, 0).WindowSent); - Assert.Equal(150, View(t, 0).WindowCap); - } - - [Fact] - public void AnExtraSendOnOneAdmission_IsCountedAndRefundedOnItsOwn() - { - long now = 0; - var t = new NodeHealthTracker(1, () => now); - Assert.Equal(NodeHealthTracker.Admission.Admitted, t.Admit(0, allowRateLimitParked: false, out _)); - var fallback = t.TryCountExtraSend(0, pastCap: false); - Assert.Equal(2, View(t, 0).WindowSent); - t.RecordRateLimited(0, 0, fallback); - t.EndAttempt(0); - Assert.Equal(1, View(t, 0).WindowSent); - } - - [Fact] - public void A429AboveTheCap_DoesNotRaiseIt() - { - long now = 0; - var t = new NodeHealthTracker(1, () => now); - Send(t, 0, 300); - Refused(t, 0); - now += 10; - // Last-resort probes go past the cap; a 429 there says the cap was right. - for (var i = 0; i < 200; i++) - { - Assert.Equal(NodeHealthTracker.Admission.Admitted, t.Admit(0, allowRateLimitParked: true)); - t.RecordSuccess(0, 50, CallClass.Cheap); - t.EndAttempt(0); - } - Refused(t, 0, probe: true); - Assert.Equal(300, View(t, 0).WindowCap); - } - - [Fact] - public void ANodeHeldAtItsCapForAWindowWithoutA429_GetsAHigherCap() - { - long now = 0; - var t = new NodeHealthTracker(1, () => now); - Send(t, 0, 400); - Refused(t, 0); - Assert.Equal(400, View(t, 0).WindowCap); - - // Steady demand: the node is met at its cap every few seconds. - for (now = 5_000; now < Window; now += 5_000) - { - Assert.Equal(NodeHealthTracker.Admission.AtCap, t.Admit(0, allowRateLimitParked: false)); - } - // The window rolls over and refills at once: still held at the cap. - now = Window; - Send(t, 0, 400); - Assert.Equal(NodeHealthTracker.Admission.AtCap, t.Admit(0, allowRateLimitParked: false)); - Assert.Equal(400, View(t, 0).WindowCap); - - // A whole window since it was first held there, no 429: the operator may - // have raised the limit, so try half as much again. - now = Window + 5_000; - Assert.Equal(NodeHealthTracker.Admission.Admitted, t.Admit(0, allowRateLimitParked: false)); - t.EndAttempt(0); - Assert.Equal(600, View(t, 0).WindowCap); - } - - [Fact] - public void AnIdleNodesCap_DoesNotGrow() - { - long now = 0; - var t = new NodeHealthTracker(1, () => now); - Send(t, 0, 400); - Refused(t, 0); - now += 10 * Window; // nothing sent: the cap was never tested - Send(t, 0, 10); - Assert.Equal(400, View(t, 0).WindowCap); - } - - [Fact] - public void ANodeThatLeftItsCap_StartsAFreshWindowBeforeItsCapGrows() - { - long now = 0; - var t = new NodeHealthTracker(1, () => now); - Send(t, 0, 400); - Refused(t, 0); - now += 10; - Assert.Equal(NodeHealthTracker.Admission.AtCap, t.Admit(0, allowRateLimitParked: false)); - - // Traffic falls: the node sits under its cap for minutes. - now += 3 * Window; - Send(t, 0, 10); - now += 6 * Window; - Send(t, 0, 400); - // At the cap again, but only just: not a window spent there. - Assert.Equal(NodeHealthTracker.Admission.AtCap, t.Admit(0, allowRateLimitParked: false)); - Assert.Equal(400, View(t, 0).WindowCap); - } - - [Fact] - public void ALastResortProbe_IsAdmittedPastTheCap() - { - long now = 0; - var t = new NodeHealthTracker(1, () => now); - Send(t, 0, 600); - Refused(t, 0); - now += 10; - Assert.Equal(NodeHealthTracker.Admission.AtCap, t.Admit(0, allowRateLimitParked: false)); - Assert.Equal(NodeHealthTracker.Admission.Admitted, t.Admit(0, allowRateLimitParked: true)); - } - - [Fact] - public void RetryAfter_ParksForItsValue_AndDoesNotAdvanceTheEscalation() - { - long now = 0; - var t = new NodeHealthTracker(1, () => now); - t.RecordRateLimited(0, 3_000); - Assert.Equal(3_000, t.RateLimitedForMs(0)); - now += 3_001; - t.RecordRateLimited(0, 3_000); - now += 3_001; - t.RecordRateLimited(0, 3_000); - now += 3_001; - // Header-less: the first step of the ladder, not a later one. - t.RecordRateLimited(0, null); - Assert.Equal(10_000, t.RateLimitedForMs(0)); - } - - [Fact] - public void AnAtCapNode_IsOfferedAsAThrottledCandidate_FreeingWhenItsOldestCallLeaves() - { - long now = 0; - var t = new NodeHealthTracker(1, () => now); - Send(t, 0, 300); // at t=0 - now = 30_000; - Send(t, 0, 300); // at t=30s - Refused(t, 0); - // The first slot frees when the calls sent at t=0 leave the window. - Assert.Equal(Window - 30_000, t.ThrottledForMs(0)); - } -} diff --git a/dotnet/EcencyApi.Tests/SsrRpcTests.cs b/dotnet/EcencyApi.Tests/SsrRpcTests.cs index 64e007dd..ac73882c 100644 --- a/dotnet/EcencyApi.Tests/SsrRpcTests.cs +++ b/dotnet/EcencyApi.Tests/SsrRpcTests.cs @@ -886,25 +886,6 @@ public async Task Stats_report_the_call_class_of_each_method_and_the_heavy_node_ Assert.Equal(1, node["samples"]!.GetValue()); Assert.Equal(1, node["heavy_samples"]!.GetValue()); Assert.NotNull(node["heavy_ewma_ms"]); - // The window cap: none before a 429 at a full window; both reads counted. - Assert.Null(node["window_cap"]); - Assert.Equal(2, node["window_sent"]!.GetValue()); - - // 150 calls in the window, then a 429: the cap is what the node accepted. - var health = SsrRpc.Client.Health; - for (var i = 0; i < 148; i++) - { - health.Admit(0, allowRateLimitParked: false, out _); - health.EndAttempt(0); - } - health.Admit(0, allowRateLimitParked: false, out var refused); - health.RecordRateLimited(0, 0, refused); - health.EndAttempt(0); - stats = Request("GET", "/private-api/ssr/stats", "right-secret"); - await SsrRpc.Stats(stats); - node = Assert.Single(JsonNode.Parse(ResponseText(stats))!["nodes"]!.AsArray())!; - Assert.Equal(150, node["window_cap"]!.GetValue()); - Assert.Equal(150, node["window_sent"]!.GetValue()); } finally { diff --git a/dotnet/EcencyApi/Infrastructure/HiveRpcClient.cs b/dotnet/EcencyApi/Infrastructure/HiveRpcClient.cs index 816b0a6e..a3276999 100644 --- a/dotnet/EcencyApi/Infrastructure/HiveRpcClient.cs +++ b/dotnet/EcencyApi/Infrastructure/HiveRpcClient.cs @@ -14,8 +14,8 @@ 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. -/// - Only one node parked for a 429 or at its window cap is asked per call -/// (the one that frees soonest, chosen after every other node was tried): while the whole pool throttles +/// - Only one node parked for a 429 is asked per call (the one whose park +/// 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 @@ -121,10 +121,6 @@ public JsonArray HealthSnapshot() node["rate_limited_for_ms"] = v.RateLimitedForMs; node["parked_for_ms"] = v.FailureParkedForMs; node["failure_rate"] = Math.Round(v.FailureRate, 3); - // The node's learned window cap (null: it never said 429 at a full - // window) and the calls sent to it in that window. - node["window_cap"] = v.WindowCap; - node["window_sent"] = v.WindowSent; // Families this node is asked the fallback for until its mark lapses. var unsupported = new JsonArray(); foreach (var m in UnsupportedFamilies(v.Index)) unsupported.Add(m); @@ -311,7 +307,7 @@ private IEnumerable UnsupportedFamilies(int nodeIndex) => var candidates = new List(deferred); while (!probeSent && candidates.Count > 0) { - var next = candidates.OrderBy(i => _health.ThrottledForMs(i)).First(); + var next = candidates.OrderBy(i => _health.RateLimitedForMs(i)).First(); candidates.Remove(next); yield return (next, true); } @@ -324,11 +320,8 @@ private IEnumerable UnsupportedFamilies(int nodeIndex) => for (var attempt = 0; attempt < _failoverThreshold; attempt++) { // Admission is decided now, under one lock with the park check. - // The counted send, refunded by exactly this ticket if answered 429. - var admission = _health.Admit(nodeIndex, allowRateLimitParked: isProbe, out var sent); - // At its window cap: as good as parked for this call, and no - // request was sent, so it is a probe candidate like a parked node. - if (admission is NodeHealthTracker.Admission.RateLimitParked or NodeHealthTracker.Admission.AtCap) + var admission = _health.Admit(nodeIndex, allowRateLimitParked: isProbe); + if (admission == NodeHealthTracker.Admission.RateLimitParked) { sawRateLimit = true; throttledNodes.Add(nodeIndex); @@ -344,7 +337,6 @@ private IEnumerable UnsupportedFamilies(int nodeIndex) => } if (isProbe) probeSent = true; var started = NowMs; - var atCapForFallback = false; try { var useFallback = fallbackBody != null && Lacks(nodeIndex, family!); @@ -361,32 +353,10 @@ private IEnumerable UnsupportedFamilies(int nodeIndex) => // per (node, family) per TTL for each call that reached the // node before the mark, and inside a fill the gate bounds. _lacksUntil[(nodeIndex, family!)] = _clock() + UnsupportedMethodTtlMs; - // A second request to the node: counted in its window, and - // a 429 to it refunds this send, not the first one. If it - // would pass the cap it is not sent; the call moves on. - var extra = _health.TryCountExtraSend(nodeIndex, pastCap: isProbe); - if (extra is null) - { - atCapForFallback = true; - result = null; - } - else - { - sent = extra; - // Rank the node on the v1 answer it will give from now on, - // not on the probe that does not recur within the TTL. - started = NowMs; - result = await TracedCallNode(nodeIndex, fallbackBody); - } - } - if (atCapForFallback) - { - // As if met at its cap: no penalty, and a probe candidate, - // where it will be asked the fallback directly. - sawRateLimit = true; - throttledNodes.Add(nodeIndex); - if (attempt == 0) deferred.Add(nodeIndex); - break; + // Rank the node on the v1 answer it will give from now on, + // not on the probe that does not recur within the TTL. + started = NowMs; + result = await TracedCallNode(nodeIndex, fallbackBody); } if (validateResult != null && !validateResult(result)) { @@ -434,7 +404,7 @@ private IEnumerable UnsupportedFamilies(int nodeIndex) => { sawRateLimit = true; throttledNodes.Add(nodeIndex); - _health.RecordRateLimited(nodeIndex, e.RetryAfterMs, sent); + _health.RecordRateLimited(nodeIndex, e.RetryAfterMs); } else { @@ -473,7 +443,7 @@ 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.ThrottledForMs(i)); + var wait = throttledNodes.Min(i => _health.RateLimitedForMs(i)); throw new UpstreamRateLimitedException( $"every RPC node is rate-limiting {method}", (int)Math.Min(int.MaxValue, wait)); } diff --git a/dotnet/EcencyApi/Infrastructure/NodeHealthTracker.cs b/dotnet/EcencyApi/Infrastructure/NodeHealthTracker.cs index b2ad7573..95aab542 100644 --- a/dotnet/EcencyApi/Infrastructure/NodeHealthTracker.cs +++ b/dotnet/EcencyApi/Infrastructure/NodeHealthTracker.cs @@ -37,10 +37,8 @@ public enum CallClass /// - Per-node health state: consecutive failures, rate-limit parking, and a /// latency EWMA used to order the pool best-first. /// - 429 parks a node for the server's Retry-After when present, else an -/// escalating window (10s doubling to 60s); only header-less 429s advance -/// the escalation, and the streak resets after 120s without a throttle. -/// Parked nodes sort last. -/// - A per-node window cap: see . +/// escalating window (10s doubling to 60s); the escalation streak resets +/// after 120s without a throttle. Parked nodes sort last. /// - A node with a recent failure (30s window) is deprioritized behind clean /// nodes, so one bad response moves traffic away without banning the node. /// - Healthy nodes are ordered by the latency EWMA of the call class being @@ -90,35 +88,6 @@ public sealed class NodeHealthTracker private const double FailureRateAlpha = 0.1; private const double FailureRateParkFloor = 0.5; - /// - /// The window cap. Several public nodes admit a fixed number of calls per - /// rolling minute from one client and answer 429 to the rest (measured: a - /// hard 600 per 60s on three of them, the same every day). Parking alone - /// cannot respect that: when a park lapses the window is usually still - /// full, and every call in flight picks the same best node, so the node is - /// overrun again at once. Instead each node counts the calls sent to it in - /// the last and, once it has said 429, is sent no more - /// than it had accepted by then: - /// - a 429 is refunded from the count (the node did not count it either), - /// and the count left becomes the cap, or lowers an existing one; - /// - a 429 to an ordinary send below that floor halves an existing cap, - /// never below the count it came at, so a limit that drops low is still - /// followed; once per burst (only a send made after the last cut - /// counts), since calls in flight together are refused together (a probe's 429 is expected and lowers nothing there); - /// - a 429 with fewer than calls in the - /// window is a burst limiter or a passing episode, not a window limit, - /// and leaves the cap alone (the park still applies); - /// - a node held at its cap for a whole window without a 429 (met there - /// again at least every ) gets half as much again, so a raised limit is found within minutes. The overshoot - /// costs the calls in flight when the 429 comes back, which snaps the cap - /// down again. - /// A node at its cap is skipped without a request or a penalty, and stays - /// a last-resort candidate (). - /// - internal const int WindowMs = 60_000; - internal const int WindowCapMinLearn = 100; - internal const int CapHeldGapMs = 10_000; - // The class is an index into each node's latency array, so CallClass values // must stay contiguous from zero. private static readonly int CallClassCount = Enum.GetValues().Length; @@ -153,16 +122,6 @@ private sealed class NodeHealth Enumerable.Range(0, CallClassCount).Select(_ => new LatencyProfile()).ToArray(); // Lifetime counters, for the stats endpoint. public long Calls, Successes, Failures, Timeouts, RateLimits; - // Send times of the attempts admitted in the last WindowMs, oldest first. - public readonly LinkedList Sent = new(); - // Learned from a 429; null until the node has said one at a full window. - public int? WindowCap; - // When the cap first held this node back since it last changed or a - // 429 came back; growth needs a whole window of that. - public long? CapHeldSinceMs; - public long LastAtCapMs; - // When a 429 below the learning floor last halved the cap. - public long CapCutAtMs = long.MinValue; } /// One node's latency for one call class, as reported by @@ -173,8 +132,7 @@ public sealed record ClassLatencyView(CallClass Class, double? EwmaMs, int Sampl public sealed record NodeView( int Index, long Calls, long Successes, long Failures, long Timeouts, long RateLimits, IReadOnlyList Latency, int ConsecutiveFailures, - bool RecentFailure, long RateLimitedForMs, long FailureParkedForMs, double FailureRate, - int? WindowCap, int WindowSent); + bool RecentFailure, long RateLimitedForMs, long FailureParkedForMs, double FailureRate); private readonly NodeHealth[] _health; private readonly object _lock = new(); @@ -265,47 +223,7 @@ public bool RecordFailure(int nodeIndex, double elapsedMs, CallClass callClass, } } - /// One send counted in a node's window (see ), - /// handed back with its 429 so exactly that send is refunded: calls answer - /// out of order, so the newest entry is not necessarily the refused one. - public sealed class SendTicket - { - internal readonly LinkedListNode Entry; - // Sent past a park or the cap as a last resort: its 429 is expected and - // says nothing new about where the limit is. - internal readonly bool Probe; - - internal SendTicket(LinkedListNode entry, bool probe) - { - Entry = entry; - Probe = probe; - } - } - - /// - /// A second request within one admitted attempt (the unknown-method - /// fallback), counted in the node's window like any other. Null when it - /// would take the node past its cap: the caller then moves on, as for a - /// node at its cap. is for the last-resort - /// probe, which was admitted past the cap already. - /// - public SendTicket? TryCountExtraSend(int nodeIndex, bool pastCap) - { - lock (_lock) - { - var now = NowMs; - var h = _health[nodeIndex]; - Prune(h, now); - if (!pastCap && h.WindowCap is { } cap && h.Sent.Count >= cap) return null; - return new SendTicket(h.Sent.AddLast(now), probe: pastCap); - } - } - - /// The refused send, from - /// or . Null for a caller that does not count - /// its sends: the node is parked and nothing is refunded or learned beyond - /// what the window already holds. - public void RecordRateLimited(int nodeIndex, int? retryAfterMs, SendTicket? sent = null) + public void RecordRateLimited(int nodeIndex, int? retryAfterMs) { lock (_lock) { @@ -319,60 +237,14 @@ public void RecordRateLimited(int nodeIndex, int? retryAfterMs, SendTicket? sent { h.RateLimitStreak = 0; } - if (retryAfterMs is { } named) - { - // The node said how long; that is not a step up our own ladder. - h.RateLimitedUntilMs = now + named; - } - else - { - h.RateLimitedUntilMs = now + Math.Min(RateLimitBaseMs << Math.Min(h.RateLimitStreak, 3), RateLimitMaxMs); - h.RateLimitStreak++; - } + var parkMs = retryAfterMs + ?? Math.Min(RateLimitBaseMs << Math.Min(h.RateLimitStreak, 3), RateLimitMaxMs); + h.RateLimitedUntilMs = now + parkMs; + h.RateLimitStreak++; h.LastRateLimitAtMs = now; - - // The window cap (see WindowMs): refund this call, learn from the rest. - // Calls in flight together are refused together: only a send made - // after the last cut is a new verdict, the rest of the burst repeats - // it. Keyed on the send, not the park, which Retry-After: 0 ends at once. - var newVerdict = sent is not null && sent.Entry.Value > h.CapCutAtMs; - if (sent?.Entry.List == h.Sent) h.Sent.Remove(sent.Entry); - Prune(h, now); - var accepted = h.Sent.Count; - if (accepted >= WindowCapMinLearn) - { - h.WindowCap = h.WindowCap is { } cap ? Math.Min(cap, accepted) : accepted; - } - else if (h.WindowCap is { } cap && sent is { Probe: false } && newVerdict) - { - // Refused inside the cap at a count too small to learn from - // outright: the limit may have dropped below the learning floor, - // or this is a passing episode. Halve towards the count, once per - // burst, so a real drop is reached in a few rounds and an episode - // costs one halving that growth recovers. - h.WindowCap = Math.Min(cap, Math.Max(Math.Max(accepted, 1), cap / 2)); - h.CapCutAtMs = now; - } - h.CapHeldSinceMs = null; } } - private static void Prune(NodeHealth h, long now) - { - while (h.Sent.First is { } oldest && oldest.Value <= now - WindowMs) h.Sent.RemoveFirst(); - } - - /// How long until the node's cap lets another call through, 0 when - /// it is under its cap or has none. - private static long CapFreesInMs(NodeHealth h, long now) - { - Prune(h, now); - if (h.WindowCap is not { } cap || h.Sent.Count < cap) return 0; - // The call whose leaving brings the count back under the cap. - var leaving = h.Sent.Skip(h.Sent.Count - cap).First(); - return Math.Max(0, leaving + WindowMs - now); - } - private void RecordLatency(NodeHealth h, CallClass callClass, double elapsedMs) { var now = NowMs; @@ -453,18 +325,6 @@ public long RateLimitedForMs(int nodeIndex) } } - /// How long until the node takes a call again: the later of its - /// 429 park and its window cap. 0 when it would be admitted now. - public long ThrottledForMs(int nodeIndex) - { - lock (_lock) - { - var now = NowMs; - var h = _health[nodeIndex]; - return Math.Max(Math.Max(0, h.RateLimitedUntilMs - now), CapFreesInMs(h, now)); - } - } - /// /// 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: @@ -476,32 +336,17 @@ public long ThrottledForMs(int nodeIndex) /// public bool TryBeginAttempt(int nodeIndex) => Admit(nodeIndex, allowRateLimitParked: true) == Admission.Admitted; - public enum Admission - { - Admitted, - RateLimitParked, - Refused, - /// The node has had as many calls this window as it accepts - /// (see ). No request was sent; like a parked node - /// it remains a last-resort candidate. - AtCap, - } + public enum Admission { Admitted, RateLimitParked, Refused } /// /// plus, when - /// is false, a node parked for a 429 is not admitted (RateLimitParked), nor a - /// node at its window cap (AtCap), decided + /// 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) => Admit(nodeIndex, allowRateLimitParked, out _); - - /// The counted send when Admitted, to hand back with a 429 - /// (); null otherwise. - public Admission Admit(int nodeIndex, bool allowRateLimitParked, out SendTicket? sent) + public Admission Admit(int nodeIndex, bool allowRateLimitParked) { - sent = null; lock (_lock) { var now = NowMs; @@ -522,31 +367,7 @@ public Admission Admit(int nodeIndex, bool allowRateLimitParked, out SendTicket? if (othersAvailable) return Admission.Refused; } if (!allowRateLimitParked && h.RateLimitedUntilMs > now) return Admission.RateLimitParked; - Prune(h, now); - if (!allowRateLimitParked && h.WindowCap is { } cap && h.Sent.Count >= cap) - { - // Held there since when: a node under steady demand meets its cap - // every time a slot frees, so a gap longer than CapHeldGapMs - // means demand fell away and the holding starts over. - if (h.CapHeldSinceMs is not { } heldSince || now - h.LastAtCapMs > CapHeldGapMs) - { - h.CapHeldSinceMs = now; - } - else if (now - heldSince >= WindowMs) - { - // A whole window at the cap and no 429: the limit may have - // been raised. Try half as much again; a 429 snaps it back. - h.WindowCap = cap + Math.Max(1, cap / 2); - h.CapHeldSinceMs = null; - } - if (h.Sent.Count >= h.WindowCap) - { - h.LastAtCapMs = now; - return Admission.AtCap; - } - } h.InFlight++; - sent = new SendTicket(h.Sent.AddLast(now), probe: allowRateLimitParked); return Admission.Admitted; } } @@ -576,17 +397,11 @@ public List Snapshot() latency, h.ConsecutiveFailures, h.ConsecutiveFailures > 0 && now - h.LastFailureAtMs < RecentFailureWindowMs, Math.Max(0, h.RateLimitedUntilMs - now), Math.Max(0, h.FailureParkedUntilMs - now), - h.FailureRate, h.WindowCap, CountInWindow(h, now)); + h.FailureRate); }).ToList(); } } - private static int CountInWindow(NodeHealth h, long now) - { - Prune(h, now); - return h.Sent.Count; - } - /// Retry-After: delta-seconds or an HTTP date (RFC 9110). public static int? ParseRetryAfterMs(string? header) {