diff --git a/dotnet/EcencyApi.Tests/HiveRpcFailoverTests.cs b/dotnet/EcencyApi.Tests/HiveRpcFailoverTests.cs index cf2baa1f..5c1c2041 100644 --- a/dotnet/EcencyApi.Tests/HiveRpcFailoverTests.cs +++ b/dotnet/EcencyApi.Tests/HiveRpcFailoverTests.cs @@ -392,6 +392,7 @@ public async Task AHealthyNodeWithOverlappingTimeouts_IsNotParked() for (var i = 0; i < 40; i++) { await client.Call("condenser_api", "get_accounts", new JsonArray()); + now += 1_000; // within the busy node's sending rate } // Three overlapping timeouts: the calls start together, each holding an // ordering with the busy node first, and all three fail on it at the @@ -732,7 +733,7 @@ public async Task AWhollyThrottledPool_CostsOneUpstreamCallPerLookup() 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 + now += 500; // inside every park (a first 429 pauses a node for 1s) await Assert.ThrowsAnyAsync(() => client.Call("condenser_api", "get_accounts", new JsonArray())); Assert.Equal(4, a.Hits + b.Hits + c.Hits); } @@ -750,7 +751,7 @@ public async Task AWhollyThrottledPool_ThrowsUpstreamRateLimited_WithTheShortest Assert.True(first.RetryAfterMs > 0); // Skipped as parked counts as throttled too, not as "no nodes". - now += 4_000; + now += 500; // inside every park (a first 429 pauses a node for 1s) var second = await Assert.ThrowsAsync(() => client.Call("condenser_api", "get_accounts", new JsonArray())); Assert.InRange(second.RetryAfterMs, 1, first.RetryAfterMs); @@ -821,7 +822,7 @@ public async Task ANodeThrottledMidCall_DoesNotTakeTheProbeFromTheSoonestPark() 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; + now = 500; // inside both parks (a first 429 pauses a node for 1s) var result = await client.Call("condenser_api", "get_accounts", new JsonArray()); Assert.Equal("served-by", result![0]!["name"]!.GetValue()); diff --git a/dotnet/EcencyApi.Tests/NodeRateLearningTests.cs b/dotnet/EcencyApi.Tests/NodeRateLearningTests.cs new file mode 100644 index 00000000..4c510225 --- /dev/null +++ b/dotnet/EcencyApi.Tests/NodeRateLearningTests.cs @@ -0,0 +1,1068 @@ +using System.Net; +using System.Text; +using System.Text.Json.Nodes; +using EcencyApi.Infrastructure; +using Xunit; + +namespace EcencyApi.Tests; + +/// +/// Learned per-node sending rates (vision-api#128): the Hive pool learns how +/// fast each node lets this host call it and stays under that, instead of +/// sending everything to the fastest node until it answers 429. +/// +public class NodeRateLearningTests +{ + private const int Pause = NodeHealthTracker.RateLimitFirstPauseMs; + + /// A node's per-IP limiter: a token bucket, like nginx limit_req. + private sealed class FakeLimiter + { + private readonly double _rate; + private readonly double _burst; + private double _tokens; + private long _at; + + public FakeLimiter(double rate, double burst, long now) + { + _rate = rate; + _burst = burst; + _tokens = burst; + _at = now; + } + + public bool Take(long now) + { + _tokens = Math.Min(_burst, _tokens + _rate * (now - _at) / 1000.0); + _at = now; + if (_tokens < 1) return false; + _tokens -= 1; + return true; + } + } + + /// + /// Demand of 3N calls/s against one node that allows N/s. Calls the node + /// has no rate for are dropped here; in the client they go to other nodes. + /// Returns (calls answered per second, share of sent calls answered 429), + /// measured after a warm-up. + /// + private static (double AnsweredPerS, double RateLimitedShare) Simulate(bool learnRates, double limit) + { + long now = 0; + var tracker = new NodeHealthTracker(1, () => now, learnRates); + var limiter = new FakeLimiter(limit, burst: limit * 2, now); + const int stepMs = 10; + var perStep = 3 * limit * stepMs / 1000.0; + double owed = 0; + long sent = 0, limited = 0; + const long warmupMs = 60_000, endMs = 240_000; + for (now = 0; now < endMs; now += stepMs) + { + owed += perStep; + while (owed >= 1) + { + owed -= 1; + var admission = tracker.Admit(0, allowRateLimitParked: false, rateUse: NodeHealthTracker.RateUse.Require); + if (admission != NodeHealthTracker.Admission.Admitted) continue; + var ok = limiter.Take(now); + if (ok) tracker.RecordSuccess(0, 50, CallClass.Cheap); + else tracker.RecordRateLimited(0, null, sentAtMs: now); + tracker.EndAttempt(0); + if (now < warmupMs) continue; + sent++; + if (!ok) limited++; + } + } + var seconds = (endMs - warmupMs) / 1000.0; + return ((sent - limited) / seconds, sent == 0 ? 0 : (double)limited / sent); + } + + [Theory] + [InlineData(4)] + [InlineData(20)] + public void ALimitedNode_IsUsedNearItsLimit_WithFewRateLimits(double limit) + { + var (answeredPerS, limitedShare) = Simulate(learnRates: true, limit); + + Assert.InRange(answeredPerS, 0.6 * limit, 1.05 * limit); + Assert.True(limitedShare < 0.05, $"429 share {limitedShare:P1}"); + } + + [Fact] + public void WithoutLearnedRates_TheSameNodeSitsParkedMostOfTheTime() + { + // The baseline the learned rate replaces, kept as a contrast (the Engine + // client still runs this way): the node is overrun, parked, overrun + // again, and answers a fraction of what it allows. + var (answeredPerS, _) = Simulate(learnRates: false, limit: 20); + + Assert.True(answeredPerS < 0.5 * 20, $"answered {answeredPerS:F1}/s of 20"); + } + + [Fact] + public void ARateLimit_HalvesTheLearnedRate_AndLimitedWindowsRaiseItAgain() + { + long now = 0; + var tracker = new NodeHealthTracker(1, () => now, learnRates: true); + var start = tracker.Snapshot()[0].RatePerS; + + tracker.RecordRateLimited(0, null); + Assert.Equal(start / 2, tracker.Snapshot()[0].RatePerS, 3); + + // Demand above the rate for several windows, all answered: it climbs. + for (var w = 0; w < 5; w++) + { + now += 2_000; // past any park + while (tracker.Admit(0, allowRateLimitParked: false, rateUse: NodeHealthTracker.RateUse.Require) == NodeHealthTracker.Admission.Admitted) + { + tracker.RecordSuccess(0, 50, CallClass.Cheap); + tracker.EndAttempt(0); + } + } + now += 1_000; + tracker.Admit(0, allowRateLimitParked: false); + Assert.True(tracker.Snapshot()[0].RatePerS > start / 2 + 1); + } + + [Fact] + public void RateLimitsInOneBurst_HalveTheRateOnce() + { + long now = 0; + var tracker = new NodeHealthTracker(1, () => now, learnRates: true); + var start = tracker.Snapshot()[0].RatePerS; + + // Calls already in flight come back 429 together: one signal, not five. + for (var i = 0; i < 5; i++) + { + tracker.RecordRateLimited(0, null); + now += 50; + } + + Assert.Equal(start / 2, tracker.Snapshot()[0].RatePerS, 3); + } + + [Fact] + public void AnIdleNode_DoesNotGrowItsRate() + { + // Growth needs demand that ran into the rate; otherwise an idle node + // would come back from a quiet hour with a rate it never proved. + long now = 0; + var tracker = new NodeHealthTracker(1, () => now, learnRates: true); + var start = tracker.Snapshot()[0].RatePerS; + for (var i = 0; i < 60; i++) + { + now += 1_000; + Assert.Equal(NodeHealthTracker.Admission.Admitted, tracker.Admit(0, allowRateLimitParked: false, rateUse: NodeHealthTracker.RateUse.Require)); + tracker.RecordSuccess(0, 50, CallClass.Cheap); + tracker.EndAttempt(0); + } + + Assert.Equal(start, tracker.Snapshot()[0].RatePerS, 3); + } + + [Fact] + public void ARetryAfter_IsHonouredExactly_WithLearnedRates() + { + long now = 0; + var tracker = new NodeHealthTracker(1, () => now, learnRates: true); + + tracker.RecordRateLimited(0, 3_000); + + Assert.Equal(3_000, tracker.RateLimitedForMs(0)); + } + + [Fact] + public void RepeatedRetryAfterRateLimits_WithNoAnswerBetween_ClimbTheLadder() + { + // A node that refuses every call while naming a short wait is still + // refusing us: honouring only its header would retry it each second. + long now = 0; + var tracker = new NodeHealthTracker(1, () => now, learnRates: true); + + tracker.RecordRateLimited(0, 1_000, sentAtMs: now); + Assert.Equal(1_000, tracker.RateLimitedForMs(0)); + + now = 1_500; + tracker.RecordRateLimited(0, 1_000, sentAtMs: now); + Assert.Equal(10_000, tracker.RateLimitedForMs(0)); + + now = 12_000; + tracker.RecordRateLimited(0, 1_000, sentAtMs: now); + Assert.Equal(20_000, tracker.RateLimitedForMs(0)); + + // An answer ends the streak: the next named wait is honoured as is. + now = 33_000; + tracker.RecordSuccess(0, 50, CallClass.Cheap); + tracker.RecordRateLimited(0, 1_000, sentAtMs: now); + Assert.Equal(1_000, tracker.RateLimitedForMs(0)); + } + + [Fact] + public void TheRate_DoesNotGrow_WhenNothingIsAnswered() + { + // Calls that never come back (a hung node) must not raise its rate + // just because more calls queued for it than it had rate for. + long now = 0; + var tracker = new NodeHealthTracker(1, () => now, learnRates: true); + var start = tracker.Snapshot()[0].RatePerS; + for (var s = 0; s < 20; s++) + { + for (var i = 0; i < 20; i++) tracker.Admit(0, allowRateLimitParked: false, NodeHealthTracker.RateUse.Require); + now += 1_000; + } + + Assert.Equal(start, tracker.Snapshot()[0].RatePerS, 3); + } + + [Fact] + public void ANewNode_DoublesItsRateUntilItsFirstRateLimit_ThenGrowsByAddition() + { + long now = 0; + var tracker = new NodeHealthTracker(1, () => now, learnRates: true); + void SaturatedSecond() + { + while (tracker.Admit(0, allowRateLimitParked: false, NodeHealthTracker.RateUse.Require) == NodeHealthTracker.Admission.Admitted) + { + tracker.RecordSuccess(0, 50, CallClass.Cheap); + tracker.EndAttempt(0); + } + now += 1_000; + } + + for (var w = 0; w < 4; w++) SaturatedSecond(); + tracker.Admit(0, allowRateLimitParked: false); // rolls the last window + tracker.EndAttempt(0); + Assert.Equal(80, tracker.Snapshot()[0].RatePerS, 3); + + tracker.RecordRateLimited(0, null, sentAtMs: now); + Assert.Equal(40, tracker.Snapshot()[0].RatePerS, 3); + now += Pause + 500; + SaturatedSecond(); + tracker.Admit(0, allowRateLimitParked: false); + tracker.EndAttempt(0); + Assert.Equal(40.5, tracker.Snapshot()[0].RatePerS, 3); + } + + [Fact] + public void OverRateOrder_PutsARecentlyRateLimitedNodeLast() + { + long now = 0; + var tracker = new NodeHealthTracker(2, () => now, learnRates: true); + tracker.RecordRateLimited(0, null, sentAtMs: now); + now = 2_000; // its pause is over, the 429 is recent + for (var i = 0; i < 10; i++) + { + tracker.Admit(1, allowRateLimitParked: false, NodeHealthTracker.RateUse.Overdraw); + tracker.EndAttempt(1); + } + + // Node 1 is deeper over its rate, but node 0 just refused a call. + Assert.Equal(new[] { 1, 0 }, tracker.OverRateOrder(new[] { 0, 1 })); + + now = 12_000; // no longer recent + Assert.Equal(0, tracker.OverRateOrder(new[] { 0, 1 })[0]); + } + + [Fact] + public void WithLearnedRates_AFirstHeaderlessRateLimit_PausesBriefly_AndRepeatsEscalate() + { + // A node at its limit gets a short pause: the halved rate is what keeps + // it from 429ing again. A node that 429s again without answering + // anything in between is refusing us, and gets the long ladder. + long now = 0; + var tracker = new NodeHealthTracker(1, () => now, learnRates: true); + + tracker.RecordRateLimited(0, null); + Assert.Equal(Pause, tracker.RateLimitedForMs(0)); + + now += Pause + 500; + tracker.RecordRateLimited(0, null); + Assert.Equal(10_000, tracker.RateLimitedForMs(0)); + + now += 11_000; + tracker.RecordSuccess(0, 50, CallClass.Cheap); + tracker.RecordRateLimited(0, null); + Assert.Equal(Pause, tracker.RateLimitedForMs(0)); + } + + [Fact] + public void WithLearnedRates_ARateLimit_IsNotARecentFailure() + { + // The halved rate is the response. Demoting the node as well left one + // at its limit idle for as long as the others could take the traffic. + long now = 0; + var learning = new NodeHealthTracker(1, () => now, learnRates: true); + var plain = new NodeHealthTracker(1, () => now); + + learning.RecordRateLimited(0, null, sentAtMs: now); + plain.RecordRateLimited(0, null); + + Assert.False(learning.Snapshot()[0].RecentFailure); + Assert.True(plain.Snapshot()[0].RecentFailure); + } + + [Fact] + public void ProbeRateLimitsFromOneBurst_ClimbOneStep_NotTheWholeLadder() + { + // Every node parked: each call in flight probes the soonest-lapsing + // one, so several probes are out when the first 429 comes back. The + // rest are the same burst; if each climbed a step, one burst would + // park the node for 60s. + long now = 0; + var tracker = new NodeHealthTracker(1, () => now, learnRates: true); + tracker.RecordRateLimited(0, null, sentAtMs: 0); // first pause + now = 1_000; + var sentAt = new List(); + for (var i = 0; i < 5; i++) + { + tracker.Admit(0, allowRateLimitParked: true, NodeHealthTracker.RateUse.Spend, out var at); + sentAt.Add(at); + now += 10; + } + foreach (var at in sentAt) + { + now += 20; + tracker.RecordRateLimited(0, null, sentAtMs: at); + tracker.EndAttempt(0); + } + + Assert.InRange(tracker.RateLimitedForMs(0), 9_000, 10_000); + } + + [Fact] + public void AfterARefusalEnds_TheRateRampsBackByDoubling() + { + // A node that refused for a while had its rate halved at each lapse. + // Once it answers again it doubles back instead of adding 0.5/s. + long now = 0; + var tracker = new NodeHealthTracker(1, () => now, learnRates: true); + for (var i = 0; i < 6; i++) + { + tracker.RecordRateLimited(0, null, sentAtMs: now); + now += 61_000; + } + var floor = tracker.Snapshot()[0].RatePerS; + Assert.True(floor < 1, $"rate {floor}"); + + for (var w = 0; w < 6; w++) + { + while (tracker.Admit(0, allowRateLimitParked: false, NodeHealthTracker.RateUse.Require) == NodeHealthTracker.Admission.Admitted) + { + tracker.RecordSuccess(0, 50, CallClass.Cheap); + tracker.EndAttempt(0); + } + now += 1_000; + } + tracker.Admit(0, allowRateLimitParked: false); + tracker.EndAttempt(0); + + Assert.True(tracker.Snapshot()[0].RatePerS >= floor * 32, $"rate {tracker.Snapshot()[0].RatePerS} from {floor}"); + } + + [Fact] + public void ALaterRateLimit_NeverShortensANamedWait() + { + long now = 0; + var tracker = new NodeHealthTracker(1, () => now, learnRates: true); + tracker.RecordRateLimited(0, 60_000, sentAtMs: 0); + + now = 1_000; // a probe's 429, a new signal: the ladder's 10s step + tracker.RecordRateLimited(0, null, sentAtMs: 1_000); + + Assert.Equal(59_000, tracker.RateLimitedForMs(0)); + } + + [Fact] + public void ANamedWait_IsHonoured_EvenFromACallSentBeforeTheDecrease() + { + long now = 0; + var tracker = new NodeHealthTracker(1, () => now, learnRates: true); + tracker.RecordRateLimited(0, null, sentAtMs: 0); + + now = 100; + tracker.RecordRateLimited(0, 5_000, sentAtMs: 0); + + Assert.Equal(5_000, tracker.RateLimitedForMs(0)); + } + + [Fact] + public void OverRateOrder_BreaksATieByFewestSentThisSecond() + { + long now = 0; + var tracker = new NodeHealthTracker(2, () => now, learnRates: true); + for (var n = 0; n < 2; n++) + { + // Both deep in debt: their waits tie at the cap. + for (var i = 0; i < 20 + n * 5; i++) + { + tracker.Admit(n, allowRateLimitParked: false, NodeHealthTracker.RateUse.Overdraw); + tracker.EndAttempt(n); + } + } + + Assert.Equal(new[] { 0, 1 }, tracker.OverRateOrder(new[] { 1, 0 })); + } + + [Fact] + public void Debt_IsCapped_SoANodeOverdrawnInABurstRecoversInSeconds() + { + long now = 0; + var tracker = new NodeHealthTracker(1, () => now, learnRates: true); + for (var i = 0; i < 1_000; i++) + { + tracker.Admit(0, allowRateLimitParked: false, NodeHealthTracker.RateUse.Overdraw); + tracker.EndAttempt(0); + } + + // A second's worth of debt at most: back within rate after about 1.2s. + now = 1_300; + Assert.Equal(NodeHealthTracker.Admission.Admitted, + tracker.Admit(0, allowRateLimitParked: false, NodeHealthTracker.RateUse.Require)); + } + + [Fact] + public void WithoutLearnedRates_AdmissionIgnoresTheRate() + { + long now = 0; + var tracker = new NodeHealthTracker(1, () => now); + for (var i = 0; i < 100; i++) + { + Assert.Equal(NodeHealthTracker.Admission.Admitted, tracker.Admit(0, allowRateLimitParked: false, rateUse: NodeHealthTracker.RateUse.Require)); + tracker.EndAttempt(0); + } + } + + // ---- through the client -------------------------------------------------- + + private sealed class LimitedStub : IAsyncDisposable + { + private readonly HttpListener _listener = new(); + private readonly Func _allow; + private readonly int _delayMs; + public string Url { get; } + public int Ok, Limited; + + /// Real time before answering, so the latency + /// ranking (measured on the real clock) prefers the other node. + public LimitedStub(Func allow, int delayMs = 0) + { + _allow = allow; + _delayMs = delayMs; + var l = new System.Net.Sockets.TcpListener(IPAddress.Loopback, 0); + l.Start(); + var port = ((IPEndPoint)l.LocalEndpoint).Port; + l.Stop(); + Url = $"http://127.0.0.1:{port}/"; + _listener.Prefixes.Add(Url); + _listener.Start(); + // Several accept loops, so calls in flight together are served together. + for (var i = 0; i < 16; i++) _ = Loop(); + } + + private async Task Loop() + { + while (_listener.IsListening) + { + HttpListenerContext ctx; + try { ctx = await _listener.GetContextAsync(); } + catch { return; } + using (var reader = new StreamReader(ctx.Request.InputStream)) await reader.ReadToEndAsync(); + if (_delayMs > 0) await Task.Delay(_delayMs); + var allowed = _allow(); + if (allowed) Interlocked.Increment(ref Ok); else Interlocked.Increment(ref Limited); + var body = Encoding.UTF8.GetBytes(allowed + ? "{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{\"by\":\"" + Url + "\"}}" + : "rate limited"); + ctx.Response.StatusCode = allowed ? 200 : 429; + ctx.Response.ContentLength64 = body.Length; + try + { + await ctx.Response.OutputStream.WriteAsync(body); + ctx.Response.Close(); + } + catch { /* client moved on */ } + } + } + + public ValueTask DisposeAsync() + { + _listener.Stop(); + _listener.Close(); + return ValueTask.CompletedTask; + } + } + + [Fact] + public async Task ALimitedNode_ServesContinuously_AndTheRestSpillsToTheNext() + { + // Both nodes are limited, together just above the demand. On the + // frozen test clock both answer in 0ms, so config order ranks the + // limited node first. + long now = 0; + var rateLimitedAt = new List(); + var limiter = new FakeLimiter(rate: 5, burst: 10, now); + var otherLimiter = new FakeLimiter(rate: 12, burst: 24, now); + var perSecondOk = new Dictionary(); + await using var fast = new LimitedStub(() => + { + var ok = limiter.Take(now); + if (ok) perSecondOk[now / 1000] = perSecondOk.GetValueOrDefault(now / 1000) + 1; + else rateLimitedAt.Add(now); + return ok; + }); + await using var other = new LimitedStub(() => otherLimiter.Take(now)); + var client = new HiveRpcClient(new[] { fast.Url, other.Url }, timeoutMs: 1000, failoverThreshold: 1, + clock: () => now); + + // 15 calls a second for 40 seconds against nodes that allow 5 and 12. + var throttled = 0; + for (var i = 0; i < 600; i++) + { + try + { + Assert.NotNull(await client.Call("condenser_api", "get_dynamic_global_properties", new JsonArray())); + } + catch (HiveRpcClient.UpstreamRateLimitedException) + { + throttled++; + } + now += 1000 / 15; + } + Assert.True(throttled < 0.02 * 600, $"{throttled} calls throttled"); + + // After warm-up the limited node keeps answering near its limit + // (5/s), whichever node ranks first; the old routing overran it and + // parked it 10 to 60s at a time. Neither node is overrun. + var fastAnswered = Enumerable.Range(10, 30).Sum(x => perSecondOk.GetValueOrDefault(x)); + Assert.True(fastAnswered >= 0.6 * 5 * 30, + $"limited node answered {fastAnswered} in 30s; per second " + + string.Join(",", Enumerable.Range(0, 40).Select(x => perSecondOk.GetValueOrDefault(x))) + + "; 429 at ms " + string.Join(",", rateLimitedAt)); + Assert.True(fast.Limited < 0.1 * fast.Ok, $"fast node: {fast.Ok} ok, {fast.Limited} 429"); + Assert.True(fast.Ok + other.Ok >= 0.95 * 600, $"answered {fast.Ok + other.Ok} of 600"); + Assert.True(other.Limited < 0.1 * other.Ok, $"other node: {other.Ok} ok, {other.Limited} 429"); + } + + [Fact] + public async Task WhenEveryNodeIsOverItsRate_EveryCallStillGoesOut_ToTheNodeThatFreesUpSoonest() + { + long now = 0; + await using var a = new LimitedStub(() => true); + await using var b = new LimitedStub(() => true); + var client = new HiveRpcClient(new[] { a.Url, b.Url }, timeoutMs: 1000, failoverThreshold: 1, clock: () => now); + + // The clock never moves, so no rate comes back: past the first two + // bucketfuls, every call finds both nodes over their rate. + for (var i = 0; i < 40; i++) + { + Assert.NotNull(await client.Call("condenser_api", "get_dynamic_global_properties", new JsonArray())); + } + + Assert.Equal(40, a.Ok + b.Ok); + // Over-rate sends go into debt, which moves the next one to the other node. + Assert.True(a.Ok > 10 && b.Ok > 10, $"a {a.Ok}, b {b.Ok}"); + var snap = client.HealthSnapshot(); + Assert.Equal(30, snap[0]!["over_rate"]!.GetValue() + snap[1]!["over_rate"]!.GetValue()); + } + + [Fact] + public async Task UnderOverload_WithManyCallsInFlight_UpstreamRequestsStayNearOnePerCall() + { + // Four nodes allowing 10/s each, asked for 80/s in batches of 50 calls + // in flight. The answered share is capped by the nodes; what this + // guards is the cost of the rest. Coming back to a node too soon after + // its 429 let the over-rate calls drain its limiter again at once, and + // each call then drew several 429s (about 1.4 requests a call with a 1s + // pause; the old 10s park cost about 1.0). + long now = 0; + var stubs = new List(); + for (var n = 0; n < 4; n++) + { + var limiter = new FakeLimiter(rate: 10, burst: 20, now); + stubs.Add(new LimitedStub(() => { lock (limiter) return limiter.Take(Interlocked.Read(ref now)); }, delayMs: n)); + } + try + { + var client = new HiveRpcClient(stubs.Select(x => x.Url).ToArray(), timeoutMs: 2000, failoverThreshold: 1, + clock: () => Interlocked.Read(ref now)); + const int calls = 80 * 40, batch = 50; + var answered = 0; + for (var i = 0; i < calls; i += batch) + { + await Task.WhenAll(Enumerable.Range(0, batch).Select(async _ => + { + try + { + await client.Call("condenser_api", "get_dynamic_global_properties", new JsonArray()); + Interlocked.Increment(ref answered); + } + catch (HiveRpcClient.UpstreamRateLimitedException) { } + })); + Interlocked.Add(ref now, 1000 * batch / 80); + } + + var upstream = stubs.Sum(x => x.Ok + x.Limited); + Assert.True(upstream < 1.15 * calls, $"{upstream} upstream requests for {calls} calls"); + // A floor against collapse only: the share answered is capped by + // the nodes (half here) and dips on a loaded runner. + Assert.True(answered > 0.4 * calls, $"answered {answered} of {calls}"); + } + finally + { + foreach (var x in stubs) await x.DisposeAsync(); + } + } + + [Fact] + public async Task UnderOverload_ACallDrawsOneOverRate429_NotOnePerNode() + { + // Both nodes take five calls, then refuse. Once both are over their + // rate, a call is sent over the rate to one of them. Its 429 moves the + // call on to the other, which has not refused anything yet; that one's + // 429 ends it. The next call meets two nodes that both refused + // recently, and draws one 429, not two. + int aLeft = 5, bLeft = 5; + await using var a = new LimitedStub(() => Interlocked.Decrement(ref aLeft) >= 0); + await using var b = new LimitedStub(() => Interlocked.Decrement(ref bLeft) >= 0); + long now = 0; + var client = new HiveRpcClient(new[] { a.Url, b.Url }, timeoutMs: 1000, failoverThreshold: 1, clock: () => now); + for (var i = 0; i < 10; i++) + { + Assert.NotNull(await client.Call("condenser_api", "get_dynamic_global_properties", new JsonArray())); + } + + await Assert.ThrowsAsync(() => + client.Call("condenser_api", "get_dynamic_global_properties", new JsonArray())); + Assert.Equal(12, a.Ok + a.Limited + b.Ok + b.Limited); + + now += Pause + 500; // past both pauses, both 429s still recent + for (var n = 0; n < 2; n++) + { + // Spend what rate came back, so both are over it again. + for (var i = 0; i < 10; i++) + { + client.Health.Admit(n, allowRateLimitParked: false, NodeHealthTracker.RateUse.Overdraw); + client.Health.EndAttempt(n); + } + } + await Assert.ThrowsAsync(() => + client.Call("condenser_api", "get_dynamic_global_properties", new JsonArray())); + Assert.Equal(13, a.Ok + a.Limited + b.Ok + b.Limited); + } + + [Fact] + public async Task TheProbe_GoesToANodeParkedLongAgo_NotOneThatJustPaused() + { + // Node 1 refused repeatedly and sits on the ladder; its last 429 is + // over 10s old and it has since recovered. Node 0 answered 429 a moment + // ago and is paused for 1s, so its park lapses first. The probe must + // still go to node 1, or a node that keeps pausing briefly takes every + // probe and recovered nodes go unnoticed until their parks run out. + await using var paused = new LimitedStub(() => false); + await using var recovered = new LimitedStub(() => true); + long now = 0; + var client = new HiveRpcClient(new[] { paused.Url, recovered.Url }, timeoutMs: 1000, failoverThreshold: 1, clock: () => now); + client.Health.RecordRateLimited(1, null, sentAtMs: now); // 1s pause + now = 1_500; client.Health.RecordRateLimited(1, null, sentAtMs: now); // 10s + now = 11_600; client.Health.RecordRateLimited(1, null, sentAtMs: now); // 20s, until 31.6s + now = 21_900; client.Health.RecordRateLimited(0, null, sentAtMs: now); // 1s pause + now = 22_000; + Assert.True(client.Health.RateLimitedForMs(0) < client.Health.RateLimitedForMs(1)); + + Assert.NotNull(await client.Call("condenser_api", "get_dynamic_global_properties", new JsonArray())); + Assert.Equal(1, recovered.Ok); + Assert.Equal(0, paused.Limited); + } + + /// A node without the v2 method: `unknown method` for it, and + /// decides the v1 fallback's status. + private sealed class OldMethodStub : IAsyncDisposable + { + private readonly HttpListener _listener = new(); + private readonly Func _v1; + private readonly Action _onV2; + public string Url { get; } + public int V2, V1; + + public OldMethodStub(Func v1, Action? onV2 = null) + { + _v1 = v1; + _onV2 = onV2 ?? (() => { }); + var l = new System.Net.Sockets.TcpListener(IPAddress.Loopback, 0); + l.Start(); + var port = ((IPEndPoint)l.LocalEndpoint).Port; + l.Stop(); + Url = $"http://127.0.0.1:{port}/"; + _listener.Prefixes.Add(Url); + _listener.Start(); + _ = Loop(); + } + + private async Task Loop() + { + while (_listener.IsListening) + { + HttpListenerContext ctx; + try { ctx = await _listener.GetContextAsync(); } + catch { return; } + string req; + using (var reader = new StreamReader(ctx.Request.InputStream)) req = await reader.ReadToEndAsync(); + int status; + string body; + if (req.Contains("get_post_v2")) + { + Interlocked.Increment(ref V2); + _onV2(); + status = 200; + body = "{\"jsonrpc\":\"2.0\",\"id\":1,\"error\":{\"code\":-32602,\"message\":\"Assert Exception:unknown method: bridge_apiget_post_v2\"}}"; + } + else + { + Interlocked.Increment(ref V1); + status = _v1(); + body = status == 200 ? "{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{\"v\":1}}" : "rate limited"; + } + var bytes = Encoding.UTF8.GetBytes(body); + ctx.Response.StatusCode = status; + ctx.Response.ContentLength64 = bytes.Length; + try + { + await ctx.Response.OutputStream.WriteAsync(bytes); + ctx.Response.Close(); + } + catch { /* client moved on */ } + } + } + + public ValueTask DisposeAsync() + { + _listener.Stop(); + _listener.Close(); + return ValueTask.CompletedTask; + } + } + + private static Task GetPostV2(HiveRpcClient client) => + client.CallMethod("bridge.get_post_v2", new JsonObject { ["author"] = "a", ["permlink"] = "p" }, + fallback: ("bridge.get_post", new JsonObject { ["author"] = "a", ["permlink"] = "p" }, "bridge.*_v2")); + + [Fact] + public async Task TheSameNodeFallback_SpendsItsOwnUnitOfRate() + { + // `unknown method` then the v1 fallback: two requests to the node, so + // two units of its rate, not one. + await using var node = new OldMethodStub(() => 200); + long now = 0; + var client = new HiveRpcClient(new[] { node.Url }, timeoutMs: 1000, failoverThreshold: 1, clock: () => now); + + Assert.NotNull(await GetPostV2(client)); + Assert.Equal(1, node.V2); + Assert.Equal(1, node.V1); + + var left = 0; + while (client.Health.Admit(0, allowRateLimitParked: false, NodeHealthTracker.RateUse.Require) == NodeHealthTracker.Admission.Admitted) + { + client.Health.EndAttempt(0); + left++; + } + Assert.Equal(3, left); // a bucket of 5, less the two requests + } + + [Fact] + public async Task AFallbacksRateLimit_IsTimedByTheFallbackItself() + { + // Between the v2 answer and the fallback, another call's 429 halves the + // node's rate and pauses it; the pause is over by the time the fallback + // goes out. The fallback is sent after that decrease, so its own 429 is + // new news and halves again; timed by the first request it would read + // as part of the earlier burst. + HiveRpcClient client = null!; + long now = 0; + await using var node = new OldMethodStub(() => 429, onV2: () => + { + now = 100; + client.Health.RecordRateLimited(0, null, sentAtMs: 100); + now = 100 + Pause + 100; + }); + client = new HiveRpcClient(new[] { node.Url }, timeoutMs: 1000, failoverThreshold: 1, clock: () => now); + var start = client.HealthSnapshot()[0]!["rate_per_s"]!.GetValue(); + + await Assert.ThrowsAsync(() => GetPostV2(client)); + + Assert.Equal(start / 4, client.HealthSnapshot()[0]!["rate_per_s"]!.GetValue(), 1); + } + + [Fact] + public async Task AFallback_IsNotSentIntoAParkThatBeganMeanwhile() + { + // Another call's 429 parks the node between the v2 answer and the + // fallback. Sending the fallback anyway would draw a 429 that counts as + // new, halving the rate again and lengthening the park. + HiveRpcClient client = null!; + long now = 0; + await using var node = new OldMethodStub(() => 200, onV2: () => + { + now = 100; + client.Health.RecordRateLimited(0, null, sentAtMs: 100); + now = 150; + }); + client = new HiveRpcClient(new[] { node.Url }, timeoutMs: 1000, failoverThreshold: 1, clock: () => now); + var start = client.HealthSnapshot()[0]!["rate_per_s"]!.GetValue(); + + await Assert.ThrowsAsync(() => GetPostV2(client)); + + Assert.Equal(0, node.V1); + Assert.Equal(start / 2, client.HealthSnapshot()[0]!["rate_per_s"]!.GetValue(), 1); + Assert.Equal(Pause - 50, client.Health.RateLimitedForMs(0)); + } + + [Fact] + public async Task AFallback_AfterAFailureParkMeanwhile_IsAnOutageNotThrottling() + { + // Concurrent calls time out and failure-park node 0 between its v2 + // answer and the fallback, while node 1 can serve. The fallback is not + // sent, and the call does not end as throttled although node 1 then + // answers 429: an outage is not a reason to advise a retry wait. + HiveRpcClient client = null!; + long now = 0; + await using var node = new OldMethodStub(() => 200, onV2: () => + { + now = 100; + while (!client.Health.RecordFailure(0, 2_000, CallClass.Cheap, timedOut: true)) { } + now = 150; + }); + await using var limited = new LimitedStub(() => false); + client = new HiveRpcClient(new[] { node.Url, limited.Url }, timeoutMs: 1000, failoverThreshold: 1, clock: () => now); + client.Health.RecordRateLimited(1, retryAfterMs: 30_000, sentAtMs: 0); + + var e = await Assert.ThrowsAnyAsync(() => GetPostV2(client)); + + Assert.Equal(1, node.V2); + Assert.Equal(0, node.V1); + Assert.IsNotType(e); + Assert.IsNotType(e); + } + + [Fact] + public async Task AFallback_AfterAFailureParkMeanwhile_IsSentWhenNoOtherNodeCanServe() + { + // The same park on the only node: a fresh call would be admitted into + // it (the pool would be empty otherwise), so the fallback is too. The + // node has just answered. + HiveRpcClient client = null!; + long now = 0; + await using var node = new OldMethodStub(() => 200, onV2: () => + { + now = 100; + while (!client.Health.RecordFailure(0, 2_000, CallClass.Cheap, timedOut: true)) { } + now = 150; + }); + client = new HiveRpcClient(new[] { node.Url }, timeoutMs: 1000, failoverThreshold: 1, clock: () => now); + + Assert.NotNull(await GetPostV2(client)); + Assert.Equal(1, node.V1); + } + + [Fact] + public async Task AWithheldFallback_ReportsTheNodeError_NotAConfigError() + { + // Node 1 is down (failure-parked, so the call cannot be only + // throttled). Node 0 answers `unknown method` and another call's 429 + // parks it before the fallback. The call ends with a node error, not + // "no RPC nodes configured". + HiveRpcClient client = null!; + long now = 0; + await using var node = new OldMethodStub(() => 200, onV2: () => + { + now = 100; + client.Health.RecordRateLimited(0, null, sentAtMs: 100); + now = 150; + }); + await using var down = new LimitedStub(() => true); + client = new HiveRpcClient(new[] { node.Url, down.Url }, timeoutMs: 1000, failoverThreshold: 1, clock: () => now); + while (!client.Health.RecordFailure(1, 2_000, CallClass.Cheap, timedOut: true)) { } + + var e = await Assert.ThrowsAnyAsync(() => GetPostV2(client)); + + Assert.Equal(0, node.V1); + Assert.IsNotType(e); + Assert.Contains("429", e.Message); + } + + [Fact] + public async Task AFallback_IsNotSent_AfterAFresh429InsideALongerPark() + { + // A probe is let into a 30s named park. Another call's probe draws a + // new 429 (rate halved, ladder 10s): shorter than the park, so the + // deadline does not move, but the node has just refused again. + HiveRpcClient client = null!; + long now = 0; + await using var node = new OldMethodStub(() => 200, onV2: () => + { + now = 1_100; + client.Health.RecordRateLimited(0, null, sentAtMs: 1_100); + now = 1_150; + }); + client = new HiveRpcClient(new[] { node.Url }, timeoutMs: 1000, failoverThreshold: 1, clock: () => now); + client.Health.RecordRateLimited(0, retryAfterMs: 30_000, sentAtMs: 0); + now = 1_000; + + await Assert.ThrowsAsync(() => GetPostV2(client)); + Assert.Equal(0, node.V1); + } + + [Fact] + public async Task AProbeIntoAPark_StillSendsItsFallback() + { + // The only node is parked by a named wait, so the call probes it. The + // probe is allowed into that park; its `unknown method` answer must + // still get the v1 fallback, or the call fails though the node answers. + await using var node = new OldMethodStub(() => 200); + long now = 0; + var client = new HiveRpcClient(new[] { node.Url }, timeoutMs: 1000, failoverThreshold: 1, clock: () => now); + client.Health.RecordRateLimited(0, retryAfterMs: 30_000, sentAtMs: 0); + now = 1_000; + + Assert.NotNull(await GetPostV2(client)); + Assert.Equal(1, node.V1); + } + + [Fact] + public async Task ARefusedCall_CountsTheNodesItLeftOut_InTheAdvisedWait() + { + // Both nodes refused at 0 and paused 1s. At 1.5s both are over their + // rate; the call sends over the rate to one, which refuses again and + // goes to the 10s step. The other was left out only for having + // refused 1.5s ago and is not parked: it is tried again once that + // refusal is 2s old, in 500ms, so that is the advice, not 10s. + await using var a = new LimitedStub(() => false); + await using var b = new LimitedStub(() => false); + long now = 0; + var client = new HiveRpcClient(new[] { a.Url, b.Url }, timeoutMs: 1000, failoverThreshold: 1, clock: () => now); + await Assert.ThrowsAsync(() => + client.Call("condenser_api", "get_dynamic_global_properties", new JsonArray())); + + now = 1_500; + for (var n = 0; n < 2; n++) + { + for (var i = 0; i < 10; i++) + { + client.Health.Admit(n, allowRateLimitParked: false, NodeHealthTracker.RateUse.Overdraw); + client.Health.EndAttempt(n); + } + } + var ex = await Assert.ThrowsAsync(() => + client.Call("condenser_api", "get_dynamic_global_properties", new JsonArray())); + + Assert.Equal(3, a.Limited + b.Limited); + Assert.Equal(500, ex.RetryAfterMs); + } + + [Fact] + public async Task AWhollyThrottledPool_AfterTheFirstPause_ClimbsTheLadder() + { + // A first 429 pauses each node briefly. If every node 429s again right + // after, without answering anything, it is refusing us: the next park + // is the 10s step, and a lookup inside it costs one probe. + await using var a = new LimitedStub(() => false); + await using var b = new LimitedStub(() => false); + await using var c = new LimitedStub(() => false); + long now = 0; + var client = new HiveRpcClient(new[] { a.Url, b.Url, c.Url }, timeoutMs: 500, failoverThreshold: 1, clock: () => now); + int Hits() => a.Limited + b.Limited + c.Limited; + + await Assert.ThrowsAsync(() => client.Call("condenser_api", "get_accounts", new JsonArray())); + Assert.Equal(3, Hits()); + + now += Pause + 500; // past the first pauses + await Assert.ThrowsAsync(() => client.Call("condenser_api", "get_accounts", new JsonArray())); + Assert.Equal(6, Hits()); + + now += 2_000; // inside the 10s step + await Assert.ThrowsAsync(() => client.Call("condenser_api", "get_accounts", new JsonArray())); + Assert.Equal(7, Hits()); + } + + [Fact] + public void RateLimitsForCallsSentBeforeTheDecrease_DoNotHalveOrParkAgain() + { + // Slow calls sent together come back 429 over several seconds, past + // any fixed hold. They predate the decrease the first one caused. + long now = 0; + var tracker = new NodeHealthTracker(1, () => now, learnRates: true); + var start = tracker.Snapshot()[0].RatePerS; + + tracker.RecordRateLimited(0, null, sentAtMs: 0); + Assert.Equal(start / 2, tracker.Snapshot()[0].RatePerS, 3); + Assert.Equal(Pause, tracker.RateLimitedForMs(0)); + + foreach (var at in new long[] { Pause + 500, 2 * Pause }) + { + now = at; + tracker.RecordRateLimited(0, null, sentAtMs: 0); + Assert.Equal(start / 2, tracker.Snapshot()[0].RatePerS, 3); + Assert.Equal(0, tracker.RateLimitedForMs(0)); + } + + // A call sent after the decrease that still draws a 429 is new news. + now = 2 * Pause + 100; + tracker.RecordRateLimited(0, null, sentAtMs: 2 * Pause); + Assert.Equal(start / 4, tracker.Snapshot()[0].RatePerS, 3); + Assert.Equal(10_000, tracker.RateLimitedForMs(0)); + } + + [Fact] + public void OverRate_CountsOnlyCallsSentOverTheRate_NotProbes() + { + long now = 0; + var tracker = new NodeHealthTracker(1, () => now, learnRates: true); + tracker.RecordRateLimited(0, 1); // empties the bucket + + tracker.Admit(0, allowRateLimitParked: true); // a probe: spends, not counted + tracker.EndAttempt(0); + Assert.Equal(0, tracker.Snapshot()[0].OverRate); + + Assert.Equal(NodeHealthTracker.Admission.OverRate, + tracker.Admit(0, allowRateLimitParked: true, NodeHealthTracker.RateUse.Require)); + Assert.Equal(NodeHealthTracker.Admission.Admitted, + tracker.Admit(0, allowRateLimitParked: true, NodeHealthTracker.RateUse.Overdraw)); + tracker.EndAttempt(0); + Assert.Equal(1, tracker.Snapshot()[0].OverRate); + } + + [Fact] + public void SentLastSecond_CountsExactlyOneAlignedSecond() + { + long now = 0; + var tracker = new NodeHealthTracker(1, () => now, learnRates: true); + void Send(long at) + { + now = at; + tracker.Admit(0, allowRateLimitParked: false); + tracker.EndAttempt(0); + } + + Send(100); Send(500); Send(900); // second 0 + Send(1_700); Send(1_950); // second 1 + now = 2_300; + Assert.Equal(2, tracker.Snapshot()[0].SentLastS); + + now = 4_100; // second 2 (empty) and 3 have passed since + Assert.Equal(0, tracker.Snapshot()[0].SentLastS); + } + + [Fact] + public async Task TheStatsShowEachNodesLearnedRate() + { + await using var only = new LimitedStub(() => true); + var client = new HiveRpcClient(new[] { only.Url }, timeoutMs: 1000, failoverThreshold: 1); + await client.Call("condenser_api", "get_dynamic_global_properties", new JsonArray()); + + var node = client.HealthSnapshot()[0]!; + + Assert.True(node["rate_per_s"]!.GetValue() > 0); + Assert.NotNull(node["sent_last_s"]); + Assert.NotNull(node["over_rate"]); + } +} diff --git a/dotnet/EcencyApi/Infrastructure/HiveRpcClient.cs b/dotnet/EcencyApi/Infrastructure/HiveRpcClient.cs index 14ef95fd..8c755f28 100644 --- a/dotnet/EcencyApi/Infrastructure/HiveRpcClient.cs +++ b/dotnet/EcencyApi/Infrastructure/HiveRpcClient.cs @@ -18,6 +18,16 @@ namespace EcencyApi.Infrastructure; /// 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 . +/// - Each node has a learned sending rate (see ). +/// A call passes over a node with no rate left, so traffic beyond what the +/// fastest node allows spills to the next one instead of overrunning it. +/// When every node is over its rate the call still goes out, over the rate +/// (order: ). A failure there +/// moves on to the next such node; after a 429, only to one that has not +/// answered 429 recently. Under real overload every node has, so a call +/// draws one over-rate 429 instead of fanning out across the pool. It does not wait for +/// rate to come back: concurrent calls would wake together and most would +/// find none anyway. /// - 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). @@ -38,6 +48,10 @@ public sealed class HiveRpcClient private readonly Func _clock; private int _seq; + /// How recent a node's 429 must be for a call that was already + /// refused to skip sending to it over the rate. + private const long RefusedRecentlyMs = 2_000; + /// Test seam: the pool's health state, to stage parks mid-call. internal NodeHealthTracker Health => _health; @@ -58,7 +72,7 @@ internal HiveRpcClient(string[] nodes, int timeoutMs, int failoverThreshold, Fun _nodes = nodes; _timeoutMs = timeoutMs; _failoverThreshold = Math.Max(1, failoverThreshold); - _health = new NodeHealthTracker(nodes.Length, clock); + _health = new NodeHealthTracker(nodes.Length, clock, learnRates: true); _clock = clock ?? (() => Environment.TickCount64); } @@ -99,6 +113,11 @@ 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 learned sending rate, what was sent in the last full second, + // and how many calls went out over the rate because no node had any. + node["rate_per_s"] = Math.Round(v.RatePerS, 1); + node["sent_last_s"] = v.SentLastS; + node["over_rate"] = v.OverRate; // 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); @@ -113,7 +132,10 @@ public sealed class RpcException : Exception public RpcException(string message) : base(message) { } } - private static long NowMs => Environment.TickCount64; + // Latency is timed on the same clock as the health state: the real one in + // production, the test's when one is injected, so a test decides the + // ranking instead of scheduler noise. + private long NowMs => _clock(); /// How many nodes may be consulted to satisfy a soft result /// preference before the first well-formed answer is accepted as-is. @@ -263,6 +285,7 @@ private IEnumerable UnsupportedFamilies(int nodeIndex) => // the advised wait is how long until the first of them can serve again. var deferred = new List(); var throttledNodes = new HashSet(); + var leftOutNodes = new HashSet(); var ordered = _health.OrderedNodeIndices(callClass); // A node left out of the ordering is parked for failing: part of the @@ -271,38 +294,95 @@ private IEnumerable UnsupportedFamilies(int nodeIndex) => // 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. A + // one since). Then ONE probe to a deferred node: one whose last 429 is + // not recent first, then the park that 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. A // candidate refused at probe time (down, or probed by another call // meanwhile) got no request, so the probe passes to the next one. + // + // Before the probe, the nodes passed over for having no rate left (they + // are not throttling us; we are holding back) are sent the call over + // their rate. A timeout or a 5xx moves on to the next. var probeSent = false; - IEnumerable<(int Node, bool Probe)> Sequence() + var overRate = new List(); + // Once this call has drawn a 429 it sends nothing more over the rate to + // a node that answered 429 in the last RefusedRecentlyMs, and no probe: + // under overload every node's own limiter is drained, and those sends + // only multiply the 429s. The window is short so that near capacity, + // where a node at its learned rate draws a 429 every several seconds, a + // single 429 does not fail the call. Calls that were not refused still + // probe, which is what finds a limit that lifted early. + var refused = false; + IEnumerable<(int Node, Pass Pass)> Sequence() { - foreach (var i in ordered) yield return (i, false); + foreach (var i in ordered) yield return (i, Pass.Ranked); + var overRateCandidates = new List(overRate); + while (overRateCandidates.Count > 0) + { + if (refused) + { + // Left out for refusing a moment ago, usually not parked: + // they count toward the wait advised if the call ends + // throttled, until they would be tried again. + foreach (var i in overRateCandidates.Where(i => _health.RateLimitedRecently(i, RefusedRecentlyMs)).ToList()) + { + overRateCandidates.Remove(i); + leftOutNodes.Add(i); + } + } + if (overRateCandidates.Count == 0) break; + var next = _health.OverRateOrder(overRateCandidates)[0]; + overRateCandidates.Remove(next); + yield return (next, Pass.OverRate); + } var candidates = new List(deferred); - while (!probeSent && candidates.Count > 0) + while (!probeSent && !refused && candidates.Count > 0) { - var next = candidates.OrderBy(i => _health.RateLimitedForMs(i)).First(); + // A node that has not answered 429 lately first: one paused + // briefly after a 429 a moment ago would otherwise always lapse + // soonest and take every probe, while nodes parked on the ladder + // that have since recovered go unnoticed until their parks end. + var next = candidates + .OrderBy(i => _health.RateLimitedRecently(i)) + .ThenBy(i => _health.RateLimitedForMs(i)) + .First(); candidates.Remove(next); - yield return (next, true); + yield return (next, Pass.Probe); } } - foreach (var (nodeIndex, isProbe) in Sequence()) + foreach (var (nodeIndex, pass) in Sequence()) { var node = _nodes[nodeIndex]; + var isProbe = pass == Pass.Probe; for (var attempt = 0; attempt < _failoverThreshold; attempt++) { // Admission is decided now, under one lock with the park check. - var admission = _health.Admit(nodeIndex, allowRateLimitParked: isProbe); + var admission = _health.Admit(nodeIndex, allowRateLimitParked: isProbe, + pass switch + { + Pass.Ranked => NodeHealthTracker.RateUse.Require, + Pass.OverRate => NodeHealthTracker.RateUse.Overdraw, + _ => NodeHealthTracker.RateUse.Spend, + }, out var sentAt, out var parkMark); + if (admission == NodeHealthTracker.Admission.OverRate) + { + // Not sent. A first look makes it an over-rate candidate; a + // same-node retry finding no rate just moves on. + if (attempt == 0) overRate.Add(nodeIndex); + break; + } if (admission == NodeHealthTracker.Admission.RateLimitParked) { sawRateLimit = true; throttledNodes.Add(nodeIndex); + // No request was sent: a real error from another node says more. + lastError ??= new NodeUnavailableException( + $"RPC node {node} is parked for a 429", advanceImmediately: true, isRateLimit: true); if (attempt == 0) deferred.Add(nodeIndex); break; } @@ -311,6 +391,8 @@ private IEnumerable UnsupportedFamilies(int nodeIndex) => // Failure-parked, or a probe of it is already in flight: an // outage, not throttling. No request was sent. sawOtherFailure = true; + lastError ??= new NodeUnavailableException( + $"RPC node {node} is parked for failing", advanceImmediately: true); break; } if (isProbe) probeSent = true; @@ -333,6 +415,30 @@ private IEnumerable UnsupportedFamilies(int nodeIndex) => _lacksUntil[(nodeIndex, family!)] = _clock() + UnsupportedMethodTtlMs; // Rank the node on the v1 answer it will give from now on, // not on the probe that does not recur within the TTL. + // A second request to the node: it spends its own unit of + // the node's rate and has its own send time. If the node + // was parked since the first request, it is not sent: a + // 429 park makes the call throttled there, a failure park + // is an outage, not throttling. + var again = _health.SpendAnother(nodeIndex, parkMark, out var fallbackAt); + if (again == NodeHealthTracker.Admission.RateLimitParked) + { + sawRateLimit = true; + throttledNodes.Add(nodeIndex); + lastError = new NodeUnavailableException( + $"RPC node {node} was parked for a 429 before the {method} fallback", + advanceImmediately: true, isRateLimit: true); + break; + } + if (again == NodeHealthTracker.Admission.Refused) + { + sawOtherFailure = true; + lastError = new NodeUnavailableException( + $"RPC node {node} was parked for failing before the {method} fallback", + advanceImmediately: true); + break; + } + sentAt = fallbackAt; started = NowMs; result = await CallNode(node, fallbackBody); } @@ -382,7 +488,10 @@ private IEnumerable UnsupportedFamilies(int nodeIndex) => { sawRateLimit = true; throttledNodes.Add(nodeIndex); - _health.RecordRateLimited(nodeIndex, e.RetryAfterMs); + // sentAt (decided under the admission lock) tells a 429 for + // a call sent before the node's last rate decrease from a new one. + _health.RecordRateLimited(nodeIndex, e.RetryAfterMs, sentAt); + refused = true; } else { @@ -421,7 +530,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)); + var wait = throttledNodes.Select(i => _health.RateLimitedForMs(i)) + .Concat(leftOutNodes.Select(i => Math.Max(_health.RateLimitedForMs(i), + _health.RateLimitedRecentlyForMs(i, RefusedRecentlyMs)))) + .Min(); throw new UpstreamRateLimitedException( $"every RPC node is rate-limiting {method}", (int)Math.Min(int.MaxValue, wait)); } @@ -431,6 +543,16 @@ private IEnumerable UnsupportedFamilies(int nodeIndex) => throw lastError ?? new InvalidOperationException("no RPC nodes configured"); } + private enum Pass + { + /// The pool in health order, within each node's rate. + Ranked, + /// The nodes passed over for their rate, now over it. + OverRate, + /// One node parked for a 429. + Probe, + } + /// /// 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. diff --git a/dotnet/EcencyApi/Infrastructure/NodeHealthTracker.cs b/dotnet/EcencyApi/Infrastructure/NodeHealthTracker.cs index 95aab542..dd45063c 100644 --- a/dotnet/EcencyApi/Infrastructure/NodeHealthTracker.cs +++ b/dotnet/EcencyApi/Infrastructure/NodeHealthTracker.cs @@ -46,6 +46,15 @@ public enum CallClass /// node that class has not proven scores a neutral prior (1s), so an unknown /// node is explored before a proven-slow one. Config order breaks ties, so /// cold start behaves exactly like the configured list. +/// - Optional learned sending rates (see the learnRates constructor +/// argument, used by the Hive pool): each node gets a rate this process may +/// call it at, learned by additive increase and multiplicative decrease. +/// A node's limit is per client IP and nodes rarely say what it is, so the +/// rate is found by probing it: it grows while calls run into it and are +/// answered, and halves on a 429. Admission can then require the rate, so +/// calls spill to the next node instead of overrunning the fastest one. +/// Several processes behind one IP converge to a share of each limit +/// without coordinating. /// public sealed class NodeHealthTracker { @@ -88,6 +97,26 @@ public sealed class NodeHealthTracker private const double FailureRateAlpha = 0.1; private const double FailureRateParkFloor = 0.5; + // Learned sending rates (learnRates only). Calls per second. + private const double InitialRatePerS = 5; + private const double MinRatePerS = 0.5; + private const double MaxRatePerS = 200; + // A window in which demand ran into the rate and no call was answered 429 + // raises the rate by this much. + private const double RateIncreasePerWindow = 0.5; + private const int RateWindowMs = 1_000; + // Calls already in flight come back 429 together. A 429 for a call sent + // before the last decrease is the same signal: no second halving, no new + // park. When the caller cannot say when its call was sent, 429s inside this + // hold after a decrease are treated as the same signal. + private const int RateDecreaseHoldMs = 1_000; + // How much of the rate may be spent at once: a second's worth. + private const double RateBurstSeconds = 1; + // With learned rates, the first header-less 429 of a streak pauses the node + // briefly (the halved rate is what keeps it from 429ing again); a 429 with + // no answer since the last one climbs the usual ladder. + public const int RateLimitFirstPauseMs = 1_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; @@ -106,9 +135,12 @@ private sealed class NodeHealth public long LastFailureAtMs; public long RateLimitedUntilMs; public int RateLimitStreak; - public long LastRateLimitAtMs; + public long LastRateLimitAtMs = long.MinValue / 4; public long FailureParkedUntilMs; public int FailureParkStreak; + // When each park last began or grew, as a ParkSeq mark: tells a park + // that began since a request was admitted from one it was let into. + public long RateParkSeq, FailureParkSeq; // Recent failure fraction (1 = every recent call failed). public double FailureRate; // Hard failures only (timeouts, refusals, bad answers), never 429s: a @@ -122,6 +154,23 @@ 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; + + // Learned sending rate (learnRates only): a token bucket refilled at + // RatePerS, holding at most a burst's worth, allowed into debt by calls + // that go out over the rate. + public double RatePerS = InitialRatePerS; + public double Tokens = InitialRatePerS * RateBurstSeconds; + public long RefilledAtMs; + public long WindowStartMs; + // Demand ran into the rate during this window / a call was answered 429. + public bool WindowLimited, WindowRateLimited, WindowAnswered; + // Until its first 429 the rate doubles per window instead of adding + // (TCP's slow start), so a restart finds each node's limit in seconds. + public bool SlowStart = true; + public int WindowSent, LastWindowSent; + public long LastDecreaseAtMs = long.MinValue / 4; + // Lifetime count of calls sent over the rate because no node had any. + public long OverRate; } /// One node's latency for one call class, as reported by @@ -132,20 +181,29 @@ 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); + bool RecentFailure, long RateLimitedForMs, long FailureParkedForMs, double FailureRate, + double RatePerS, int SentLastS, long OverRate); private readonly NodeHealth[] _health; private readonly object _lock = new(); + // Bumped under the lock each time a park begins or grows (see SpendAnother). + private long _parkSeq; private readonly Func _clock; + private readonly bool _learnRates; - public NodeHealthTracker(int nodeCount, Func? clock = null) + /// Learn a sending rate per node and let admission + /// require it (see the class summary). Off, admission ignores rates and a + /// header-less 429 parks on the 10/20/40/60s ladder from the first one. + public NodeHealthTracker(int nodeCount, Func? clock = null, bool learnRates = false) { + _clock = clock ?? (() => Environment.TickCount64); + _learnRates = learnRates; + var now = _clock(); _health = new NodeHealth[nodeCount]; for (var i = 0; i < nodeCount; i++) { - _health[i] = new NodeHealth(); + _health[i] = new NodeHealth { RefilledAtMs = now, WindowStartMs = now }; } - _clock = clock ?? (() => Environment.TickCount64); } private long NowMs => _clock(); @@ -165,6 +223,12 @@ public void RecordSuccess(int nodeIndex, double elapsedMs, CallClass callClass) h.FailureRate *= 1 - FailureRateAlpha; h.ConsecutiveFailures = 0; h.ConsecutiveHardFailures = 0; + // An answer after 429s that climbed the ladder ends a refusal, not a + // node at its limit: each lapse of the park halved the rate again, + // down to the floor. Ramp back by doubling, as at start (TCP restarts + // slow start after a timeout), so the node is not underused for + // minutes once it serves again. + if (_learnRates && h.RateLimitStreak >= 2) h.SlowStart = true; h.RateLimitStreak = 0; h.FailureParkStreak = 0; // A node that just answered is not parked, whatever the deadline said: @@ -172,6 +236,11 @@ public void RecordSuccess(int nodeIndex, double elapsedMs, CallClass callClass) // not be pushed out again by a stale deadline the moment another // node's park lapses. h.FailureParkedUntilMs = 0; + if (_learnRates) + { + Refill(h, NowMs); + h.WindowAnswered = true; + } RecordLatency(h, callClass, elapsedMs); } } @@ -217,13 +286,18 @@ public bool RecordFailure(int nodeIndex, double elapsedMs, CallClass callClass, { var parkMs = Math.Min(FailureParkBaseMs << Math.Min(h.FailureParkStreak, 2), FailureParkMaxMs); h.FailureParkedUntilMs = now + parkMs; + h.FailureParkSeq = ++_parkSeq; h.FailureParkStreak++; } return h.FailureParkedUntilMs > now; } } - public void RecordRateLimited(int nodeIndex, int? retryAfterMs) + /// When the call that drew the 429 was admitted, on + /// this tracker's clock (as + /// returns it). With learned rates it tells a 429 that predates the last + /// decrease (already acted on) from a new one. + public void RecordRateLimited(int nodeIndex, int? retryAfterMs, long? sentAtMs = null) { lock (_lock) { @@ -231,20 +305,182 @@ public void RecordRateLimited(int nodeIndex, int? retryAfterMs) var now = NowMs; h.Calls++; h.RateLimits++; - h.ConsecutiveFailures++; - h.LastFailureAtMs = now; + if (!_learnRates) + { + // Without learned rates a 429 also demotes the node behind clean + // ones for a while. With them, the halved rate is the response: + // demoting too would leave a node at its limit idle for as long + // as the others can absorb the traffic. + h.ConsecutiveFailures++; + h.LastFailureAtMs = now; + } if (now - h.LastRateLimitAtMs > RateLimitStreakResetMs) { h.RateLimitStreak = 0; } - var parkMs = retryAfterMs - ?? Math.Min(RateLimitBaseMs << Math.Min(h.RateLimitStreak, 3), RateLimitMaxMs); - h.RateLimitedUntilMs = now + parkMs; - h.RateLimitStreak++; + // One burst of 429s is one signal (see RateDecreaseHoldMs). + var sameBurst = _learnRates && (sentAtMs is { } sent + ? sent <= h.LastDecreaseAtMs + : now - h.LastDecreaseAtMs < RateDecreaseHoldMs); + if (_learnRates) + { + Refill(h, now); + h.WindowRateLimited = true; + if (!sameBurst) + { + h.RatePerS = Math.Max(MinRatePerS, h.RatePerS / 2); + h.SlowStart = false; + h.LastDecreaseAtMs = now; + h.Tokens = Math.Min(h.Tokens, 0); + } + } + if (!_learnRates) + { + var parkMs = retryAfterMs + ?? Math.Min(RateLimitBaseMs << Math.Min(h.RateLimitStreak, 3), RateLimitMaxMs); + h.RateLimitedUntilMs = now + parkMs; + h.RateParkSeq = ++_parkSeq; + h.RateLimitStreak++; + } + else if (sameBurst) + { + // Already acted on: the decrease and the park it set. A wait the + // server names is still honoured. + if (retryAfterMs is { } named) + { + ExtendRatePark(h, now + named); + } + } + else + { + // The first 429 of a streak: the server's wait if it named one, + // else a short pause (the halved rate does the rest). A repeat + // with no answer in between is a refusal, whatever the header + // says: at least the next step of the ladder. + var ladderMs = h.RateLimitStreak == 0 + ? RateLimitFirstPauseMs + : Math.Min(RateLimitBaseMs << Math.Min(h.RateLimitStreak - 1, 3), RateLimitMaxMs); + var parkMs = retryAfterMs is { } named + ? (h.RateLimitStreak == 0 ? named : Math.Max(named, ladderMs)) + : ladderMs; + // Never shorten a park already in force: a wait the server + // named earlier still stands. A new refusal all the same, even + // when the park does not grow (see SpendAnother). + ExtendRatePark(h, now + parkMs); + h.RateParkSeq = ++_parkSeq; + h.RateLimitStreak++; + } h.LastRateLimitAtMs = now; } } + /// Some other node is neither failure-parked nor busy half-open. + /// Call under the lock. + private bool OthersAvailable(int nodeIndex, long now) + { + for (var j = 0; j < _health.Length; j++) + { + if (j == nodeIndex) continue; + var o = _health[j]; + var oParked = o.FailureParkedUntilMs > now; + var oBusy = !oParked && o.FailureParkStreak > 0 && o.InFlight > 0; + if (!oParked && !oBusy) return true; + } + return false; + } + + private void ExtendRatePark(NodeHealth h, long untilMs) + { + if (untilMs <= h.RateLimitedUntilMs) return; + h.RateLimitedUntilMs = untilMs; + h.RateParkSeq = ++_parkSeq; + } + + private static double BurstCapacity(NodeHealth h) => Math.Max(1, h.RatePerS * RateBurstSeconds); + + /// Brings the node's bucket and rate window up to now. + private static void Refill(NodeHealth h, long now) + { + if (now > h.RefilledAtMs) + { + h.Tokens = Math.Min(BurstCapacity(h), h.Tokens + h.RatePerS * (now - h.RefilledAtMs) / 1000.0); + h.RefilledAtMs = now; + } + var windows = (now - h.WindowStartMs) / RateWindowMs; + if (windows >= 1) + { + // Growth needs demand that ran into the rate and was answered: an + // idle node must not come back with a rate it never proved, and a + // node that answers nothing must not grow because calls queued for it. + if (h.WindowLimited && h.WindowAnswered && !h.WindowRateLimited) + { + h.RatePerS = Math.Min(MaxRatePerS, + h.SlowStart ? h.RatePerS * 2 : h.RatePerS + RateIncreasePerWindow); + } + // Windows stay aligned, so the count is for exactly one second. + h.LastWindowSent = windows == 1 ? h.WindowSent : 0; + h.WindowSent = 0; + h.WindowLimited = false; + h.WindowRateLimited = false; + h.WindowAnswered = false; + h.WindowStartMs += windows * RateWindowMs; + } + } + + /// How long until the node's last 429 is + /// old, 0 when it already is. + public long RateLimitedRecentlyForMs(int nodeIndex, long withinMs) + { + lock (_lock) + { + return Math.Max(0, _health[nodeIndex].LastRateLimitAtMs + withinMs - NowMs); + } + } + + /// The node answered 429 within the last + /// (default ). + public bool RateLimitedRecently(int nodeIndex, long withinMs = RateLimitBaseMs) + { + lock (_lock) + { + return NowMs - _health[nodeIndex].LastRateLimitAtMs < withinMs; + } + } + + private static long OverRateForMs(NodeHealth h) => + h.Tokens >= 1 ? 0 : (long)Math.Ceiling((1 - h.Tokens) / h.RatePerS * 1000); + + /// + /// The order to send a call over the rate to these nodes (learned rates): + /// a node that answered 429 in the last last, + /// since sending over its rate is likeliest to draw another; then the one + /// that frees up soonest; then the one sent the fewest calls this second. + /// The last breaks the tie under sustained overload, where every node's + /// debt sits at its cap and the excess would otherwise all go to one node. + /// + public List OverRateOrder(IEnumerable nodeIndices) + { + lock (_lock) + { + var now = NowMs; + return nodeIndices + .Select(i => + { + var h = _health[i]; + if (_learnRates) Refill(h, now); + return (Index: i, + Recent: now - h.LastRateLimitAtMs < RateLimitBaseMs, + Wait: _learnRates ? OverRateForMs(h) : 0, + Sent: h.WindowSent); + }) + .OrderBy(x => x.Recent) + .ThenBy(x => x.Wait) + .ThenBy(x => x.Sent) + .Select(x => x.Index) + .ToList(); + } + } + private void RecordLatency(NodeHealth h, CallClass callClass, double elapsedMs) { var now = NowMs; @@ -336,7 +572,18 @@ public long RateLimitedForMs(int nodeIndex) /// public bool TryBeginAttempt(int nodeIndex) => Admit(nodeIndex, allowRateLimitParked: true) == Admission.Admitted; - public enum Admission { Admitted, RateLimitParked, Refused } + public enum Admission { Admitted, RateLimitParked, Refused, OverRate } + + /// How a call admitted with learned rates uses the node's rate. + public enum RateUse + { + /// Spend one unit, into debt if there is none (a probe). + Spend, + /// No rate left: OverRate, not admitted. + Require, + /// Sent over the rate if there is none, and counted as such. + Overdraw, + } /// /// plus, when @@ -344,34 +591,88 @@ public enum Admission { Admitted, RateLimitParked, Refused } /// 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 . + /// + /// With learned rates every admitted call spends one unit of the node's + /// rate; says what happens when none is left. + /// Ignored without learned rates. Every call counts as one unit whatever + /// its class: the limiters in front of public nodes count requests, not + /// their cost. /// - public Admission Admit(int nodeIndex, bool allowRateLimitParked) + public Admission Admit(int nodeIndex, bool allowRateLimitParked, RateUse rateUse = RateUse.Spend) => + Admit(nodeIndex, allowRateLimitParked, rateUse, out _); + + /// + /// The time admission was decided, under the same + /// lock: pass it to as the send time. + public Admission Admit(int nodeIndex, bool allowRateLimitParked, RateUse rateUse, out long admittedAtMs) => + Admit(nodeIndex, allowRateLimitParked, rateUse, out admittedAtMs, out _); + + /// + /// Marks the parks in force at admission: pass it to + /// for a further request in the same attempt. + public Admission Admit(int nodeIndex, bool allowRateLimitParked, RateUse rateUse, out long admittedAtMs, out long parkMark) { lock (_lock) { var now = NowMs; + admittedAtMs = now; + parkMark = _parkSeq; var h = _health[nodeIndex]; var parked = h.FailureParkedUntilMs > now; var halfOpenBusy = !parked && h.FailureParkStreak > 0 && h.InFlight > 0; - if (parked || halfOpenBusy) + if ((parked || halfOpenBusy) && OthersAvailable(nodeIndex, now)) return Admission.Refused; + if (!allowRateLimitParked && h.RateLimitedUntilMs > now) return Admission.RateLimitParked; + if (_learnRates) { - var othersAvailable = false; - for (var j = 0; j < _health.Length && !othersAvailable; j++) + Refill(h, now); + if (h.Tokens < 1) { - if (j == nodeIndex) continue; - var o = _health[j]; - var oParked = o.FailureParkedUntilMs > now; - var oBusy = !oParked && o.FailureParkStreak > 0 && o.InFlight > 0; - othersAvailable = !oParked && !oBusy; + h.WindowLimited = true; + if (rateUse == RateUse.Require) return Admission.OverRate; + if (rateUse == RateUse.Overdraw) h.OverRate++; } - if (othersAvailable) return Admission.Refused; + h.Tokens = Math.Max(h.Tokens - 1, -BurstCapacity(h)); + h.WindowSent++; } - if (!allowRateLimitParked && h.RateLimitedUntilMs > now) return Admission.RateLimitParked; h.InFlight++; return Admission.Admitted; } } + /// + /// A further request inside an attempt already admitted (the same-node + /// fallback after an `unknown method`): it spends one more unit of the + /// node's rate, into debt if none is left, without counting as over-rate, + /// since no node was chosen for it. is its send + /// time, decided under the lock, for . + /// + /// Not sent into a park that began since the first request was admitted + /// (, from Admit): Refused for a failure park (an + /// outage) when another node can serve, as Admit has it; RateLimitParked + /// for a 429 park, or a 429 inside one. A park the first request was let + /// into (a probe) does not stop it: the node has just answered. + /// + public Admission SpendAnother(int nodeIndex, long parkMark, out long sentAtMs) + { + lock (_lock) + { + var now = NowMs; + sentAtMs = now; + var h = _health[nodeIndex]; + if (h.FailureParkedUntilMs > now && h.FailureParkSeq > parkMark && OthersAvailable(nodeIndex, now)) + return Admission.Refused; + if (h.RateLimitedUntilMs > now && h.RateParkSeq > parkMark) return Admission.RateLimitParked; + if (_learnRates) + { + Refill(h, now); + if (h.Tokens < 1) h.WindowLimited = true; + h.Tokens = Math.Max(h.Tokens - 1, -BurstCapacity(h)); + h.WindowSent++; + } + return Admission.Admitted; + } + } + public void EndAttempt(int nodeIndex) { lock (_lock) @@ -390,6 +691,7 @@ public List Snapshot() return Enumerable.Range(0, _health.Length).Select(i => { var h = _health[i]; + if (_learnRates) Refill(h, now); var latency = Enumerable.Range(0, CallClassCount) .Select(c => new ClassLatencyView((CallClass)c, h.Latency[c].EwmaMs, h.Latency[c].SampleCount)) .ToList(); @@ -397,7 +699,7 @@ 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.FailureRate, _learnRates ? h.RatePerS : 0, h.LastWindowSent, h.OverRate); }).ToList(); } }