Skip to content

Commit 075baef

Browse files
committed
fix(metrics): mirror the guarded tip into smartrouter_latest_block on every poll observation
MAG-2629 — the router-wide latest-block gauge was written only in the relay- harvest path (SetRouterLatestBlock had exactly one call site), while the ChainState tip it reports has TWO feeders: polls and relay harvest. On a router serving no relay traffic the gauge froze at the last relay's value as polls kept the real tip fresh — dashboards read "falling behind head" on an idle pod, indistinguishable from a genuinely stuck tip, and contradicting the poll-fed rpc_endpoint_latest_block beside it. Archaeology: T3 rewired the gauge to the guarded tip in the relay path; Topic C later added the poll feeder to ChainState and no matching metric write came with it. The OnTipObservation closure becomes a named method (onTipObservation) that feeds ChainState as before and then mirrors the gated GetLatestBlock() into the gauge. Same only-when-fresh semantics as the relay-path write: a stale tip leaves the gauge alone (zeroing would turn TTL expiry into a false "chain reset"), and the gauge always carries the GUARDED tip, never the raw block, so a lying-high endpoint cannot inflate it through this path either. The harvest- path write stays — redundant now, kept as the explicit relay-side guarantee. Regression pin: TestOnTipObservation_GaugeAdvancesUnderPollOnlyTraffic drives the hook with poll-only traffic and requires the gauge to seed, advance, and hold under a warped-stale read; verified to FAIL against the pre-fix wiring ("smartrouter_latest_block not reported"). The gauge-reading helper is lifted to file scope and shared with the existing harvest-path test. Verified live against ETH1 mainnet (PublicNode + Tenderly, zero relays sent): pre-fix gauge +0 over 65s while endpoints advanced +6; post-fix gauge +3 over 40s, 1 block behind the live head. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Took 2 hours 27 minutes
1 parent 8205771 commit 075baef

2 files changed

Lines changed: 123 additions & 29 deletions

File tree

‎protocol/rpcsmartrouter/chainstate_glue_test.go‎

Lines changed: 78 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -368,31 +368,7 @@ func TestHarvest_ArchiveRoutingTipGuardedByChainState(t *testing.T) {
368368
mm := metrics.NewSmartRouterMetricsManager(metrics.SmartRouterMetricsManagerOptions{})
369369
require.NotNil(t, mm)
370370

371-
// routerLatestBlock reads the smartrouter_latest_block GAUGE for this chain/interface. Unlike the
372-
// counters elsewhere in this package it is Set to an ABSOLUTE value, and these tests run
373-
// sequentially (no t.Parallel), so the value read straight after a harvest is the one that
374-
// harvest reported — no before/after delta needed.
375-
routerLatestBlock := func(t *testing.T) float64 {
376-
t.Helper()
377-
mfs, err := prometheus.DefaultGatherer.Gather()
378-
require.NoError(t, err)
379-
for _, mf := range mfs {
380-
if mf.GetName() != "smartrouter_latest_block" {
381-
continue
382-
}
383-
for _, m := range mf.GetMetric() {
384-
lm := map[string]string{}
385-
for _, lp := range m.GetLabel() {
386-
lm[lp.GetName()] = lp.GetValue()
387-
}
388-
if lm["spec"] == "ETH1" && lm["apiInterface"] == "jsonrpc" {
389-
return m.GetGauge().GetValue()
390-
}
391-
}
392-
}
393-
require.FailNow(t, "smartrouter_latest_block not reported for ETH1/jsonrpc")
394-
return 0
395-
}
371+
routerLatestBlock := readRouterLatestBlockGauge
396372

397373
cs := chainstate.NewWithClock("ETH1", chainstate.Config{
398374
BucketWidth: 2,
@@ -655,3 +631,80 @@ func TestSiteC_InClusterEndpointChargedNoSyncGap(t *testing.T) {
655631
require.Equal(t, width+1, syncGapAgainstReference(tip, mode-1, width),
656632
"just past BucketWidth the endpoint is charged its real distance")
657633
}
634+
635+
// readRouterLatestBlockGauge reads the smartrouter_latest_block GAUGE for ETH1/jsonrpc off the
636+
// default registry. Unlike the counters elsewhere in this package it is Set to an ABSOLUTE value,
637+
// and these tests run sequentially (no t.Parallel), so the value read straight after a write is
638+
// the one that write reported — no before/after delta needed. Shared by the relay-harvest test
639+
// (TestHarvest_ArchiveRoutingTipGuardedByChainState) and the poll-path test below (MAG-2629).
640+
func readRouterLatestBlockGauge(t *testing.T) float64 {
641+
t.Helper()
642+
mfs, err := prometheus.DefaultGatherer.Gather()
643+
require.NoError(t, err)
644+
for _, mf := range mfs {
645+
if mf.GetName() != "smartrouter_latest_block" {
646+
continue
647+
}
648+
for _, m := range mf.GetMetric() {
649+
lm := map[string]string{}
650+
for _, lp := range m.GetLabel() {
651+
lm[lp.GetName()] = lp.GetValue()
652+
}
653+
if lm["spec"] == "ETH1" && lm["apiInterface"] == "jsonrpc" {
654+
return m.GetGauge().GetValue()
655+
}
656+
}
657+
}
658+
require.FailNow(t, "smartrouter_latest_block not reported for ETH1/jsonrpc")
659+
return 0
660+
}
661+
662+
// MAG-2629 regression pin: the router-wide latest-block gauge must advance under POLL-ONLY
663+
// traffic. Before the fix, SetRouterLatestBlock had exactly one call site — the relay-harvest
664+
// path — so on a router serving no relays the gauge froze at the last relay's value while the
665+
// poll-fed ChainState tip (and the per-endpoint gauges next to it) kept advancing: dashboards
666+
// read "falling behind head" on an idle pod, indistinguishable from a genuinely stuck tip.
667+
//
668+
// onTipObservation is the EndpointMonitor's OnTipObservation hook — the exact function every
669+
// accepted poll observation drives in production — called here directly so the test needs no
670+
// tracker, upstream, or relay machinery: the point is that THIS path alone must keep the gauge
671+
// live. Verified to fail against the pre-fix wiring (hook = bare SetLatestBlock closure).
672+
func TestOnTipObservation_GaugeAdvancesUnderPollOnlyTraffic(t *testing.T) {
673+
// Empty options => metrics registered on the default registry, no HTTP server started.
674+
mm := metrics.NewSmartRouterMetricsManager(metrics.SmartRouterMetricsManagerOptions{})
675+
require.NotNil(t, mm)
676+
677+
// Real clock + DefaultConfig, exactly as ServeRPCRequests wires it (TTL = 10×13s = 130s),
678+
// so the fresh-path assertions run under production freshness semantics.
679+
cs := chainstate.New("ETH1", chainstate.DefaultConfig(13*time.Second))
680+
681+
rpcss := &RPCSmartRouterServer{
682+
chainState: cs,
683+
smartRouterEndpointMetrics: mm,
684+
listenEndpoint: &lavasession.RPCEndpoint{ChainID: "ETH1", ApiInterface: "jsonrpc"},
685+
}
686+
687+
// Two consecutive poll observations — no relay anywhere in this test — must move the gauge.
688+
rpcss.onTipObservation(25_638_537)
689+
require.Equal(t, float64(25_638_537), readRouterLatestBlockGauge(t),
690+
"first poll observation must seed the gauge — pre-fix, only a relay could")
691+
rpcss.onTipObservation(25_638_545)
692+
require.Equal(t, float64(25_638_545), readRouterLatestBlockGauge(t),
693+
"the gauge must track the tip under poll-only traffic — the frozen-gauge case from MAG-2629")
694+
695+
// Only-when-fresh semantics, shared with the relay-path write: warp the ChainState clock past
696+
// TTL (stamps stay on the real clock, evaluation is warped — the same mechanism harness
697+
// scenario 4 pins), so the gated GetLatestBlock reports stale. A poll observation arriving in
698+
// that state must leave the gauge UNTOUCHED: a stale tip must not advance it, and zeroing it
699+
// would turn routine TTL expiry into a false "chain reset" on the graph.
700+
cs.SetDebugClockOffset(200 * time.Second)
701+
rpcss.onTipObservation(25_638_600)
702+
require.Equal(t, float64(25_638_545), readRouterLatestBlockGauge(t),
703+
"a stale gated read must leave the gauge at its last fresh value")
704+
cs.SetDebugClockOffset(0)
705+
706+
// Nil-guards: fixtures build servers without metrics or ChainState wired — the hook fires
707+
// from tracker callbacks and must never panic on such a server.
708+
(&RPCSmartRouterServer{}).onTipObservation(1)
709+
(&RPCSmartRouterServer{chainState: cs}).onTipObservation(1)
710+
}

‎protocol/rpcsmartrouter/rpcsmartrouter_server.go‎

Lines changed: 45 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -217,10 +217,9 @@ func (rpcss *RPCSmartRouterServer) ServeRPCRequests(
217217
ApiInterface: listenEndpoint.ApiInterface,
218218
AverageBlockTime: effectiveBlockTime,
219219
BlocksToSave: endpointstate.DefaultBlocksToSave,
220-
// Feed every positive poll/relay block into the per-chain tip (cheap monotonic write).
221-
OnTipObservation: func(block int64) {
222-
rpcss.chainState.SetLatestBlock(block)
223-
},
220+
// Feed every positive poll/relay block into the per-chain tip (cheap monotonic write)
221+
// and mirror the resulting guarded tip into the router-wide latest-block gauge (MAG-2629).
222+
OnTipObservation: rpcss.onTipObservation,
224223
OnNewBlock: func(endpointURL string, fromBlock, toBlock int64) {
225224
utils.LavaFormatTrace("endpoint ChainTracker detected new block",
226225
utils.LogAttr("endpoint", endpointURL),
@@ -2451,6 +2450,43 @@ func runProbeCycleCore(
24512450
return scored, reEnabled, syncOmitted
24522451
}
24532452

2453+
// onTipObservation is the EndpointMonitor's OnTipObservation hook: it feeds every positive
2454+
// poll/relay block into the per-chain ChainState tip, then mirrors the resulting GUARDED tip into
2455+
// the router-wide smartrouter_latest_block gauge.
2456+
//
2457+
// MAG-2629 — the gauge mirror lives HERE, on the hook that advances the tip, because the gauge
2458+
// used to be written only in the relay-harvest path (harvestAndUpdateTipFromRelay below). The tip
2459+
// itself has two feeders — polls and relay harvest — so on a router serving no relay traffic the
2460+
// gauge froze at the last relay's value while polls kept the real tip fresh: dashboards read
2461+
// "falling behind head" on an idle pod, indistinguishable from a genuinely stuck tip, and
2462+
// contradicting the poll-fed rpc_endpoint_latest_block right next to it. Writing it where the tip
2463+
// changes makes the metric a faithful mirror under poll-only traffic; the harvest-path write
2464+
// remains (redundant, not wrong) as the relay-side immediacy guarantee.
2465+
//
2466+
// Only-when-fresh semantics, same as the harvest-path write: the gated GetLatestBlock returns
2467+
// ok=false when the tip is stale, and the gauge is then left alone — a stale tip must not advance
2468+
// it, and zeroing it would turn routine TTL expiry into a false "chain reset" on the graph. The
2469+
// gauge always carries the guarded tip, never the raw observed block, so a lying-high endpoint
2470+
// cannot inflate it through this path either.
2471+
//
2472+
// Nil-guards cover test fixtures that construct the server without metrics or ChainState wired.
2473+
func (rpcss *RPCSmartRouterServer) onTipObservation(block int64) {
2474+
if rpcss.chainState == nil {
2475+
return
2476+
}
2477+
rpcss.chainState.SetLatestBlock(block)
2478+
if rpcss.smartRouterEndpointMetrics == nil || rpcss.listenEndpoint == nil {
2479+
return
2480+
}
2481+
if accepted, ok := rpcss.chainState.GetLatestBlock(); ok {
2482+
rpcss.smartRouterEndpointMetrics.SetRouterLatestBlock(
2483+
rpcss.listenEndpoint.ChainID,
2484+
rpcss.listenEndpoint.ApiInterface,
2485+
accepted,
2486+
)
2487+
}
2488+
}
2489+
24542490
// harvestAndUpdateTipFromRelay applies a served relay's block to TIP state — but only when the
24552491
// response is tip-eligible (MAG-2159 finding 4). tipBlockFromRelay distinguishes a "block
24562492
// associated with a response" (historical: eth_getBlockByNumber(N), getBlockByHash,
@@ -2495,6 +2531,11 @@ func (rpcss *RPCSmartRouterServer) harvestAndUpdateTipFromRelay(
24952531
// guarded tip (not the raw harvested `tip`) keeps a lying-high endpoint out of the router-wide
24962532
// metric, the scope the old chain-accepted gate protected. The per-endpoint metric below stays
24972533
// gated on the store only: it reports THIS endpoint's own view.
2534+
//
2535+
// Since MAG-2629 this is no longer the gauge's only writer: onTipObservation (the hook above)
2536+
// refreshes it on every accepted poll observation too, so the gauge no longer freezes on a
2537+
// router serving no relay traffic. This write is now redundant on the relay path (the hook has
2538+
// already fired by this point) and is kept as the explicit relay-side guarantee.
24982539
if rpcss.chainState != nil && rpcss.smartRouterEndpointMetrics != nil {
24992540
if accepted, ok := rpcss.chainState.GetLatestBlock(); ok {
25002541
rpcss.smartRouterEndpointMetrics.SetRouterLatestBlock(

0 commit comments

Comments
 (0)