Skip to content

Commit 07dc208

Browse files
Tomelia1999claude
andcommitted
fix(rpcsmartrouter): the re-verify hold-off reads the urls the pass dials (MAG-4733)
Since MAG-4214 (#659) a re-verify pass verifies the dialed urls: on a chain with internal paths a bare url becomes one url per path. The hold-off entries, the skip set and the per-url pass results were still positions into the configured list, so on TON, STRK, AVAX and Monero a 429 from a generated url was never held, a relay hold on one was not honoured, and a held pinned url was asked while a free sibling was skipped. holdoffEntries and heldOffUntil now build from reverifyNodeUrls, the list the pass verifies (dialedNodeUrls). The relay path already records a 429 under the dialed url, so the keys line up and the per-path known limitation goes away. Found in review (PR #618). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 265d9ed commit 07dc208

8 files changed

Lines changed: 157 additions & 29 deletions

‎docs/RATE-LIMIT-HOLDOFF.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -100,8 +100,8 @@ off" means on its path. This table is the catalog; add a row when wiring a new c
100100

101101
| Path | What "held off" means there | Records into the registry | Status |
102102
| --- | --- | --- | --- |
103-
| Spec re-verification (`spec_reverifier.go`) | A held url is not asked: the pass reads it as only rate-limited, so it keeps its last verdict — its url refusal and the refusals of its add-ons, since none of its checks ran — and the provider's other urls are still checked — a url refused for a capability problem comes back while a sibling is busy (MAG-4733). Only when every url is held is the probe skipped, returning the rate-limit error so reconciliation stays inconclusive — membership unchanged, streak untouched — without spending a request | 429 from `Validate`, under the url that answered it (MAG-4733): a relay url under the provider entry's key, a websocket url under the url alone (the WS path's key), so a socket's 429 never counts toward the entry's escalation. Results are merged per url (one url configured twice is one url) and every 429 is recorded before any answer, so the outcome does not depend on config order and an answer never clears a 429 the same pass met on the same url. Each url that answered clears its own entry; a url the pass did not send a request to (held off, or a retry kept its verdicts without dialing it) changes nothing, and a pass that never ran (a config error) clears nothing | live |
104-
| Verification retries (`verification_retry.go`, MAG-3950) | A failing check's next retry is scheduled no earlier than the first of its provider's urls comes out of its hold-off, whatever its backoff says: the pass asks only the urls that are not held, so one free url is enough (MAG-4733); a provider retried while still in the pairing goes through the spec re-verification row's probe, so a held provider is not probed | through spec re-verification's probe; the retry of a provider out of the pairing records nothing | live |
103+
| Spec re-verification (`spec_reverifier.go`) | The urls are the ones the router dials, so on a chain with internal paths a bare url is one url per path (`base + path`, the key the relay path records a 429 under), each held, skipped and cleared on its own (MAG-4214). A held url is not asked: the pass reads it as only rate-limited, so it keeps its last verdict — its url refusal and the refusals of its add-ons, since none of its checks ran — and the provider's other urls are still checked — a url refused for a capability problem comes back while a sibling is busy (MAG-4733). Only when every url is held is the probe skipped, returning the rate-limit error so reconciliation stays inconclusive — membership unchanged, streak untouched — without spending a request | 429 from `Validate`, under the url that answered it (MAG-4733): a relay url under the provider entry's key, a websocket url under the url alone (the WS path's key), so a socket's 429 never counts toward the entry's escalation. Results are merged per url (one url configured twice is one url) and every 429 is recorded before any answer, so the outcome does not depend on config order and an answer never clears a 429 the same pass met on the same url. Each url that answered clears its own entry; a url the pass did not send a request to (held off, or a retry kept its verdicts without dialing it) changes nothing, and a pass that never ran (a config error) clears nothing | live |
104+
| Verification retries (`verification_retry.go`, MAG-3950) | A failing check's next retry is scheduled no earlier than the first of its provider's dialed urls comes out of its hold-off, whatever its backoff says: the pass asks only the urls that are not held, so one free url is enough (MAG-4733); a provider retried while still in the pairing goes through the spec re-verification row's probe, so a held provider is not probed | through spec re-verification's probe; the retry of a provider out of the pairing records nothing | live |
105105
| Hot relay path (endpoint selection) | A rate-limited relay releases its session with no QoS sample in either direction, and selection prefers providers that are not held off — a provider is held only while every url of it that could serve the request is held — and inside a provider it hands out a url that is not held before one that is (MAG-4732), except in the last chance, which first ranks a url by its state — in rotation, then head-stalled, then switched off — and keeps this order only within a rank (MAG-4734); when every candidate is held off, the soonest-to-expire one stays in — the customer is never answered with a synthesized 429. A write broadcast is the exception: a stateful request goes to every enabled provider, held off or not — primaries, and backups under `--stateful-to-backup` — because the hold-off chooses which provider a request goes to and a broadcast goes to all of them. A provider still limiting answers the write with a 429, which is not the answer, so the broadcast waits for the others; one that has recovered lands it (MAG-4388). A write that reaches a single provider keeps the hold-off: a sticky write, the fleet claim a write proposes for a new sticky session, and every write under the cost strategy, which does not broadcast | 429 relay results, both shapes (typed HTTP error, 2xx-body/gRPC classification) | live |
106106
| Recovery probe (`recovery_probe.go`) | Skip the replay while held off (verdict stays inconclusive), instead of burning replay-attempt budget on a vendor that said stop | 429 probe responses (Retry-After floor honoured) | live |
107107
| Chain tracker / endpoint poller (`chaintracker/chain_tracker.go`, `endpointstate/endpoint_monitor.go`) | Records its own 429s under the url alone — the key the WS and gRPC subscription paths use — never under the relay path's (provider, url) key: relay selection holds a provider off while every url of it that could serve the request is held, so a tracker entry there would hold a relay url off whenever its tracker is limited, and a backup-tier leg with no relay traffic would never be cleared. Reads both keys: the first fetch waits out an existing hold-off before each attempt, and a rate-limited attempt ends the init burst instead of retrying into the limit — the applied hold-off rides the start error as its Retry-After, and the monitor's start retry waits it out with the tracker in `retrying_start` naming the 429, never `starting` with no error; the dedicated poll waits out the applied hold-off (Retry-After when sent, else the strike schedule) and whatever the registry holds for the url — a relay's, a probe's or a subscription's hold-off, or the provider escalation. Its timer wakes at the normal cadence and reads the registry on every wake: while the url is held off nothing is sent, not even the poll scheduled before the hold-off began, and the next wake looks again (MAG-4387). It used to fold the hold-off into one timer when the timer was armed, so a poll already scheduled went out into the limit and a hold-off lifted early was slept out in full — after a burst of 429s that froze the url's tip for up to 35 minutes while relays on the url were answered. The idle wake burst does not poll a url that is held off: `WakePoll` sends nothing and returns `chaintracker.ErrorPollNowHeldOff` (also the typed 429, remaining wait as Retry-After), and the burst counts the url as not polled. An explicit `/debug/poll-now` still polls, as an explicit `lava-select-provider` outranks a relay hold-off. Because each wake reads the registry, an answer recorded for the url by anyone — a relay included — resumes the poll within one interval. A held wake runs at the base cadence, not the failure backoff: a refused poll counts as a failed one, and the backoff it built up would otherwise delay the resume by up to a minute. Clears its url-only entry only after its own 429 was answered; a fetch that got no answer (timeout, refused or reset connection) clears nothing | The typed 429 from the head or block-hash fetch — an HTTP 429, a refused ws handshake, or a JSON-RPC error body with code 429 / "too many requests", which `chainlib.RateLimitedReplyError` types for the body form on both fetchers — `chainlib.ChainFetcher` and the per-endpoint `endpointstate.EndpointPoller` behind every per-url tracker, including its `CustomMessage` behind the SVM (Solana / KOII) latest-slot poll via `chainlib.RateLimitedErrorBody` (MAG-4165) | live |

‎protocol/rpcsmartrouter/per_url_admission_test.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -324,7 +324,7 @@ func TestApplyReverification_AnAddonsOwnRateLimitHoldsNothing(t *testing.T) {
324324
require.Contains(t, collectNames(next), provider.Name)
325325
require.Empty(t, demoted)
326326
require.Contains(t, up.methods("http", "/q/"+upTraceRate), "trace_block", "the add-on's check was asked, or this test proves nothing")
327-
_, held := holdoffs.ProviderReadyAt(holdoff.ProviderKey("ETH1", "jsonrpc", provider.Name), holdoffURLKeys(provider))
327+
_, held := holdoffs.ProviderReadyAt(holdoff.ProviderKey("ETH1", "jsonrpc", provider.Name), holdoffURLKeys(provider, nil))
328328
require.False(t, held, "relay selection still serves the provider")
329329
services, keep := admissions.admissionFor(provider).AdmittedServices(provider.NodeUrls[1])
330330
require.True(t, keep)
Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
package rpcsmartrouter
2+
3+
import (
4+
"fmt"
5+
"net/http"
6+
"net/http/httptest"
7+
"sync"
8+
"testing"
9+
10+
commonlib "github.com/magma-Devs/smart-router/protocol/common"
11+
"github.com/magma-Devs/smart-router/protocol/holdoff"
12+
"github.com/magma-Devs/smart-router/protocol/routersession"
13+
spectypes "github.com/magma-Devs/smart-router/types/spec"
14+
"github.com/stretchr/testify/require"
15+
)
16+
17+
// newLimitedTon is a TON node that answers 429 to every path, counting the requests by path.
18+
func newLimitedTon(t *testing.T) (*httptest.Server, func(path string) int) {
19+
t.Helper()
20+
var mu sync.Mutex
21+
hits := map[string]int{}
22+
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
23+
mu.Lock()
24+
hits[r.URL.Path]++
25+
mu.Unlock()
26+
w.Header().Set("Content-Type", "application/json")
27+
w.Header().Set("Retry-After", "60")
28+
w.WriteHeader(http.StatusTooManyRequests)
29+
fmt.Fprint(w, `{"error":"rate limited"}`)
30+
}))
31+
t.Cleanup(srv.Close)
32+
return srv, func(path string) int {
33+
mu.Lock()
34+
defer mu.Unlock()
35+
return hits[path]
36+
}
37+
}
38+
39+
func tontReverifyInputs(t *testing.T, provider *routersession.RPCStaticProviderEndpoint, holdoffs *holdoff.Registry) (*chainReverifyInputs, *admissionRegistry) {
40+
t.Helper()
41+
admissions := newAdmissionRegistry()
42+
return &chainReverifyInputs{
43+
chainParser: tontParser(t),
44+
rpcEndpoint: &routersession.RPCEndpoint{ChainID: "TONT", ApiInterface: spectypes.APIInterfaceRest},
45+
convertProvidersToSessions: fakeConvert,
46+
configuredStatic: []*routersession.RPCStaticProviderEndpoint{provider},
47+
recordAdmission: admissions.record,
48+
recordReverifiedAdmission: admissions.recordReverified,
49+
admissionFor: admissions.admissionFor,
50+
rateLimitHoldoff: holdoffs,
51+
}, admissions
52+
}
53+
54+
// Since MAG-4214 a re-verify pass verifies the urls the router dials: on a chain with internal
55+
// paths a bare url is one url per path. The hold-off reads and writes the same list, so the
56+
// url a 429 came from, the url a relay hold is on, and the url the pass skips are one url
57+
// (found in review, PR #618). On TONT a bare base url A dials A/v2 and A/v3.
58+
func TestReverifyHoldoff_UsesTheDialedURLs(t *testing.T) {
59+
t.Run("a 429 from a generated url is held on that url", func(t *testing.T) {
60+
a := newFakeTon(t, tontRootHash)
61+
c, _ := newLimitedTon(t)
62+
provider := tontProvider(commonlib.NodeUrl{Url: a.srv.URL}, commonlib.NodeUrl{Url: c.URL})
63+
key := holdoff.ProviderKey("TONT", spectypes.APIInterfaceRest, provider.Name)
64+
holdoffs := holdoff.NewRegistry()
65+
inputs, admissions := tontReverifyInputs(t, provider, holdoffs)
66+
active := map[uint64]*routersession.ConsumerSessionsWithProvider{0: makeSession(provider.Name)}
67+
68+
applyReverification(t.Context(), inputs, active, reverifyTierStatic, 100)
69+
require.NotNil(t, admissions.admissionFor(provider).URLRateLimit(2), "the pass met the 429 on dialed index 2 (C/v2)")
70+
require.True(t, holdoffs.HeldOff(key, c.URL+"/v2"), "the url that answered 429 is held")
71+
require.False(t, holdoffs.HeldOff(key, a.srv.URL+"/v2"), "A/v2 answered")
72+
})
73+
74+
t.Run("a relay hold on a generated url is honoured", func(t *testing.T) {
75+
a := newFakeTon(t, tontRootHash)
76+
c, hits := newLimitedTon(t)
77+
provider := tontProvider(commonlib.NodeUrl{Url: a.srv.URL}, commonlib.NodeUrl{Url: c.URL})
78+
key := holdoff.ProviderKey("TONT", spectypes.APIInterfaceRest, provider.Name)
79+
holdoffs := holdoff.NewRegistry()
80+
holdoffs.RecordRateLimit(key, c.URL+"/v2", 0) // what the relay path records for C/v2
81+
inputs, _ := tontReverifyInputs(t, provider, holdoffs)
82+
active := map[uint64]*routersession.ConsumerSessionsWithProvider{0: makeSession(provider.Name)}
83+
84+
applyReverification(t.Context(), inputs, active, reverifyTierStatic, 100)
85+
require.Zero(t, hits("/v2/getMasterchainInfo"), "the held url is not asked")
86+
require.NotZero(t, a.asked("/v2/getMasterchainInfo"), "the free url is")
87+
})
88+
89+
t.Run("a held pinned url is skipped, not a free sibling", func(t *testing.T) {
90+
a := newFakeTon(t, tontRootHash)
91+
b, hits := newLimitedTon(t)
92+
pinned := commonlib.NodeUrl{Url: b.URL + "/v2", InternalPath: "/v2"}
93+
provider := tontProvider(commonlib.NodeUrl{Url: a.srv.URL}, pinned)
94+
key := holdoff.ProviderKey("TONT", spectypes.APIInterfaceRest, provider.Name)
95+
holdoffs := holdoff.NewRegistry()
96+
holdoffs.RecordRateLimit(key, pinned.Url, 0)
97+
inputs, _ := tontReverifyInputs(t, provider, holdoffs)
98+
active := map[uint64]*routersession.ConsumerSessionsWithProvider{0: makeSession(provider.Name)}
99+
100+
applyReverification(t.Context(), inputs, active, reverifyTierStatic, 100)
101+
require.Zero(t, hits("/v2/getMasterchainInfo"), "the held url B/v2 is not asked")
102+
require.NotZero(t, a.asked("/v2/getMasterchainInfo"), "A/v2 is asked")
103+
})
104+
105+
t.Run("the retry wait reads the dialed urls", func(t *testing.T) {
106+
const base = "https://ton.example"
107+
provider := tontProvider(commonlib.NodeUrl{Url: base})
108+
parser := tontParser(t)
109+
key := holdoff.ProviderKey("TONT", spectypes.APIInterfaceRest, provider.Name)
110+
require.Equal(t, []holdoffEntry{{provider: key, url: base + "/v2"}, {provider: key, url: base + "/v3"}},
111+
holdoffEntries(key, provider, parser), "heldOffUntil and the pass read the same entries")
112+
reg := holdoff.NewRegistry()
113+
reg.RecordRateLimit(key, base+"/v2", 0)
114+
require.True(t, heldOffUntil(reg, provider, parser).IsZero(), "/v3 is free, so a retry need not wait")
115+
})
116+
}

‎protocol/rpcsmartrouter/reverify_holdoff_test.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -159,7 +159,7 @@ func TestReverify_ProviderPassingOnItsOtherUrlKeepsTheDeadUrlsStrikes(t *testing
159159
start := time.Date(2026, 8, 20, 12, 0, 0, 0, time.UTC)
160160
now := start
161161
reg := holdoff.NewRegistryWithClock(func() time.Time { return now })
162-
urlKey := holdoffURLKeys(provider)[0]
162+
urlKey := holdoffURLKeys(provider, nil)[0]
163163
require.Equal(t, refusing, urlKey, "the hold-off is keyed by the refusing url")
164164
reg.RecordRateLimit(holdoff.ProviderKey("ETH1", "jsonrpc", provider.Name), urlKey, 0)
165165

‎protocol/rpcsmartrouter/reverify_url_holdoff_test.go‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ func TestRecordPassHoldoffs_AWebsocketRateLimitDoesNotHoldTheEntry(t *testing.T)
6363
common.NodeUrl{Url: "https://b"},
6464
)
6565
key := holdoff.ProviderKey("ETH1", "jsonrpc", provider.Name)
66-
entries := holdoffEntries(key, provider)
66+
entries := holdoffEntries(key, provider, nil)
6767
require.Equal(t, holdoffEntry{provider: "wss://a", url: "wss://a"}, entries[1])
6868

6969
reg := holdoff.NewRegistry()
@@ -245,12 +245,12 @@ func TestHeldOffUntil_OneFreeURLIsEnough(t *testing.T) {
245245
reg := holdoff.NewRegistry()
246246
reg.RecordRateLimit(key, "https://b", 30*time.Second)
247247
reg.RecordRateLimit("wss://a", "wss://a", 0)
248-
require.True(t, heldOffUntil(reg, provider).IsZero(), "a is free")
248+
require.True(t, heldOffUntil(reg, provider, nil).IsZero(), "a is free")
249249

250250
reg.RecordRateLimit(key, "https://a", 0)
251-
until := heldOffUntil(reg, provider)
251+
until := heldOffUntil(reg, provider, nil)
252252
require.False(t, until.IsZero(), "every url held")
253-
for _, entry := range holdoffEntries(key, provider) {
253+
for _, entry := range holdoffEntries(key, provider, nil) {
254254
require.False(t, until.After(reg.ReadyAt(entry.provider, entry.url)), "the first url to come out")
255255
}
256256
}

‎protocol/rpcsmartrouter/rpcsmartrouter.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3037,7 +3037,7 @@ func (rpsr *RPCSmartRouter) CreateSmartRouterEndpoint(
30373037
for _, p := range tier.providers {
30383038
if _, failed := tier.failed[p]; !failed {
30393039
inputs.countRefusals(tier.tier, p, admissionFor(p))
3040-
inputs.retries.reconcile(tier.tier, p.Name, nil, inputs.retriesOf(p, admissionFor(p), nil), heldOffUntil(nil, p), true)
3040+
inputs.retries.reconcile(tier.tier, p.Name, nil, inputs.retriesOf(p, admissionFor(p), nil), heldOffUntil(nil, p, inputs.chainParser), true)
30413041
}
30423042
}
30433043
}
@@ -4560,7 +4560,7 @@ func (rpsr *RPCSmartRouter) revalidateTier(
45604560
// One back with something still failing, a url still refused, stays on the
45614561
// schedule for what still fails.
45624562
inputs.retries.reconcile(tier, provider.Name, result.ran, inputs.retriesOf(provider, result.admission, nil),
4563-
heldOffUntil(inputs.rateLimitHoldoff, provider), countAttempt)
4563+
heldOffUntil(inputs.rateLimitHoldoff, provider, inputs.chainParser), countAttempt)
45644564
}
45654565
recovered = append(recovered, provider)
45664566
utils.FormatInfo("[+] provider recovered and passed verification",

0 commit comments

Comments
 (0)