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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
129 changes: 0 additions & 129 deletions dotnet/EcencyApi.Tests/HiveRpcFailoverTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1031,133 +1031,4 @@ public async Task AllNodesDown_Throws()
await Assert.ThrowsAnyAsync<Exception>(() =>
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<long>();
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<Exception>(() => 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);
}
}
Loading
Loading